Flask Basic HTTP Auth使用登录页面

时间:2015-02-28 16:27:18

标签: python flask http-basic-authentication

我正在构建测试应用并使用此处的说明(http://flask.pocoo.org/snippets/8/)来设置简单身份验证。在需要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

看起来我可以使用Flask-Auth,但我真的只需要上面提供的功能。

谢谢, 莱恩

1 个答案:

答案 0 :(得分:4)

从文档中,这里:http://flask.pocoo.org/docs/0.10/patterns/viewdecorators/。有一个样本装饰器就是这样做的:

from functools import wraps
from flask import g, request, redirect, url_for

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if g.user is None:
            return redirect(url_for('login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function

只需返回重定向,而不是像现在一样调用authenticate()方法。