我正在构建一个测试应用程序,并使用了此处的说明(http://flask.pocoo.org/snippets/8/)以设置简单的身份验证。在需要授权的页面上,我会看到一个弹出窗口,上面写着"需要授权"。相反,我想重定向到一个登录页面,在那里用户可以将他们的用户/通行证放入表单中
以下是我目前拥有的(与链接中的片段相同):
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,但我真的只需要上面提供的功能。
谢谢,Ryan
从文档中,这里: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()方法。