Python-falcon处理会话

时间:2017-02-09 15:26:43

标签: python session web falcon

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

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

1 个答案:

答案 0 :(得分:0)

对于非常简单的应用程序,HTTP Basic Auth可能已经足够好了。 Flask使这很容易。以下装饰器应用于仅对某些用户可用的函数:

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