繁体   English   中英

Python-falcon处理会话

[英]Python-falcon handling session

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

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

对于非常简单的应用程序,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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM