Python 请求前烧瓶 - 为特定路线添加例外
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14367991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
flask before request - add exception for specific route
提问by SeanPlusPlus
In the before_request()function (below), I want to redirect the user to /loginif they are not yet logged in. Is there a special variable that will give me the current URL that will work as the below example does?
在before_request()函数(下面)中,/login如果用户尚未登录,我想将用户重定向到。是否有一个特殊的变量可以为我提供当前的 URL,它将像下面的示例一样工作?
@app.before_request
def before_request():
# the variable current_url does not exist
# but i want something that works like it
if (not 'logged_in' in session) and (current_url != '/login'):
return redirect(url_for('login'))
I need to check that the current URL is /login, because if I don't the server goes into an infinite loop.
我需要检查当前 URL 是否为/login,因为如果我不这样做,服务器将进入无限循环。
采纳答案by DazWorrall
There are a couple of properties on the request object you can check, documented here, request.pathis probably what you want. Can I suggest request.endpointthough, so you'll be covered should you decide to route your view to another url, or multiple urls
您可以检查请求对象上的几个属性,记录在这里,request.path可能是您想要的。我可以建议request.endpoint吗,所以如果您决定将视图路由到另一个 url 或多个 url,您将被覆盖
@app.before_request
def before_request():
if 'logged_in' not in session and request.endpoint != 'login':
return redirect(url_for('login'))
回答by savepopulation
You can use a decorator. Here's an example that shows how to check an API key before specific requests:
您可以使用装饰器。下面的示例展示了如何在特定请求之前检查 API 密钥:
from functools import wraps
def require_api_key(api_method):
@wraps(api_method)
def check_api_key(*args, **kwargs):
apikey = request.headers.get('ApiKey')
if apikey and apikey == SECRET_KEY:
return api_method(*args, **kwargs)
else:
abort(401)
return check_api_key
And you can use it with:
您可以将其用于:
@require_api_key
回答by Ryne Everett
Here's an implementation of the accepted answer with flask-login:
这是使用flask-login实现的已接受答案:
@app.before_request
def require_authorization():
from flask import request
from flask.ext.login import current_user
if not (current_user.is_authenticated or request.endpoint == 'login'):
return login_manager.unauthorized()

