Python猎鹰处理会话



我正在使用python-flask构建一个简单的web应用程序,用户可以在其中点击路径localhost:8000/并登录。如果登录成功,会显示另一个页面,但我想知道,如果用户已经登录,我如何重定向到主页?例如,如果我第一次登录,我会被带到主页,如果我打开第二个选项卡,再次点击url登录,我就会自动重定向到主页(很像gmail?)。

class LoginPage(object):
def on_get(self, req, resp, form={}):

对于非常简单的应用程序,HTTP Basic Auth可能已经足够好了。烧瓶使这件事变得非常容易。以下围绕一个仅对某些用户可用的函数应用的装饰器正是这样做的:

from functools import wraps
from flask import request, Response
def check_auth(username, password):
"""This function is called to check if a username password combination is valid. """
return username == 'admin' and password == 'secret'
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):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated

要使用这个装饰器,只需包装一个视图函数:

@app.route('/secret-page')
@requires_auth
def secret_page():
return render_template('secret_page.html')

如果您在mod_wsgi中使用基本身份验证,则必须启用身份验证转发,否则apache将使用所需的标头,并且不会将其发送到您的应用程序:WSGIPassAuthorization。

最新更新