我正在提供要查看的静态文件,需要基本的登录名和密码。目前我只是使用此代码段:http://flask.pocoo.org/snippets/8/
现在它一直保持活动状态,直到浏览器退出。我想弄清楚如何写一个简单的超时。像“如果它是5分钟,杀死它并将用户重定向回索引页面。
我非常接近,超时,只有在浏览器窗口仍处于打开状态时才会记住重定向。关于如何处理最后一部分的任何建议?一块饼干?会话结算?还有别的吗?
由于
def check_auth(username, password):
#This function is called to check if a username / password combination is valid.
return username == 'oneshot' and password == 'private'
def authenticate():
# Sends a 401 response that enables basic auth
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
start_time = session.get('session_time', None)
if start_time is None:
start_time = datetime.datetime.now()
session['session_time'] = start_time
elapsed = datetime.datetime.now() - start_time
if datetime.timedelta(0, 60, 0) < elapsed:
return redirect(url_for('index'))
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
答案 0 :(得分:0)
这是我最终做的事情:
def login_required(test):
@wraps(test)
def wrap(*args, **kwargs):
if 'logged_in' in session:
# session is always none
start_time = session.get('session_time', None)
#get the current time and set it as start time, this is also your session timer start
if start_time is None:
start_time = datetime.datetime.now()
session['session_time'] = start_time
# make an end time 1 minute from now
end_time = start_time + datetime.timedelta(minutes=1)
#find the current time in a for loop maybe? or just an if will probably work.
if datetime.datetime.now() > end_time:
return redirect(url_for('expired', next=request.url))
session.clear()
start_time = session.get('session_time', None)
return test(*args, **kwargs)
else:
return redirect(url_for('login', next=request.url))
return wrap
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
return redirect(url_for('media'))
return render_template('login.html', error=error)
@app.route('/expired')
def expired():
session.clear()
return render_template('expired.html')