我正在使用Flask-HTTPAuth来处理我的应用中的身份验证。我有很多观点,我不想在其中的每一个中添加login_required
。如何默认登录?
from flask.ext.httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
@auth.verify_password
def verify_password(username, password):
return username == '111' and password == '222'
@app.route('/')
@app.route('/home/')
@auth.login_required
def index():
return 'Hello'
@app.route('/route2/')
def route2():
return 'route2'
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
答案 0 :(得分:8)
默认情况下,您可以添加before_request
函数以要求登录,并为少数不需要登录的路径创建一个简单的login_exempt
装饰器。
确保免除静态文件,否则不会为未经身份验证的用户加载。
Flask-HTTPAuth的login_required
没有办法将需要逻辑与视图装饰器分开,你需要通过一个小舞蹈来要求auth而不运行视图。
def login_exempt(f):
f.login_exempt = True
return f
# a dummy callable to execute the login_required logic
login_required_dummy_view = auth.login_required(lambda: None)
@app.before_request
def default_login_required():
# exclude 404 errors and static routes
# uses split to handle blueprint static routes as well
if not request.endpoint or request.endpoint.rsplit('.', 1)[-1] == 'static':
return
view = current_app.view_functions[request.endpoint]
if getattr(view, 'login_exempt', False):
return
return login_required_dummy_view()
# for example, the login page shouldn't require login
@app.route('/login', methods=['GET', 'POST'])
@login_exempt
def login():
pass