【发布时间】:2014-06-30 04:45:02
【问题描述】:
我正在提供一个静态文件,需要基本登录名和密码才能查看。目前我只是在使用这个 sn-p: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
【问题讨论】:
标签: python session redirect flask basic-authentication