请求前烧瓶-为特定路线添加异常

在下面的 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'))

我需要检查当前的 URL 是否是 /login,因为如果我不这样做,服务器将进入一个无限循环。

84550 次浏览

There are a couple of properties on the request object you can check, documented here, request.path is probably what you want. Can I suggest request.endpoint though, so you'll be covered should you decide to route your view to another url, or multiple urls

@app.before_request
def before_request():
if 'logged_in' not in session and request.endpoint != 'login':
return redirect(url_for('login'))

You can use a decorator. Here's an example that shows how to check an API key before specific requests:

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

Here's an implementation of the accepted answer with 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()