像这样的问题:我使用Flask-Login
的login_required装饰现在Best way to make Django's login_required the default最好的方法,使烧瓶登录的login_required默认
。无论如何,使它成为Flask
的默认行为?
像这样的问题:我使用Flask-Login
的login_required装饰现在Best way to make Django's login_required the default最好的方法,使烧瓶登录的login_required默认
。无论如何,使它成为Flask
的默认行为?
我在我的instruments项目中做了这个。我用的是before_request
装饰:
@app.before_request
def check_valid_login():
login_valid = 'user' in session # or whatever you use to check valid login
if (request.endpoint and
'static' not in request.endpoint and
not login_valid and
not getattr(app.view_functions[request.endpoint], 'is_public', False)) :
return render_template('login.html', next=request.endpoint)
,然后我创建了一个is_public()
装饰为将需要访问,无需登录了几个地方:
def public_endpoint(function):
function.is_public = True
return function
我认为'静态'不在request.endpoint不是很正确 - 可能像request.endpoint =='static',或request.endpoint.startswith('static /')? – nonagon
为什么你检查了'request.endpoint' –
如果您使用的蓝图和需要保护的整个蓝图用登录,可以使整个before_request
需要登录。
这是我用我的CMS蓝图:
@cms.before_request
@login_required
def before_request():
if g.user.role != ROLE_ADMIN:
abort(401)
如果你只需要检查,如果用户登录(而不是用户是否有权限),你可以简单地pass
功能
也许你可以覆盖像full_dispatch_request()这样的函数并在那里执行逻辑,然后在验证通过的情况下调用真实视图。更多关于这个函数和其他API函数的地方(你可以找到你需要的函数)http://flask.pocoo.org/docs/api/#flask.Flask.full_dispatch_request或者首先你可以尝试before_request装饰器,但不知道如果您将拥有该状态下所需的所有数据。自己没有这样做,所以抱歉不能给出更准确的答案或代码示例。 –
你能澄清你的意思是“默认行为”吗?你的意思是所有的视图函数默认都应该有login_required? – codegeek
@codegeek是的,除了我可以在配置文件中定义的一些白名单视图。 – yegle