Flask:before_request检查会话和/或cookie无法正常工作

时间:2014-06-16 16:10:03

标签: python flask

这是我的代码:

blueprint = Blueprint('client', __name__, template_folder='templates')

@blueprint.before_request
def load_session_from_cookie():
    account = check_sso_cookie(request.cookies, for_view=False)

    # if error occurred, return error
    if 'message' in account:
        session.pop('accountId', None)
        return redirect(settings.LOGIN_URL)

    if 'accountId' in session:
        return redirect(url_for('home'))
    elif 'accountId' in account:
        session['accountId'] = account.get('accountId')
        return redirect(url_for('home'))
    else:
        session.pop('accountId', None)
        return redirect(settings.LOGIN_URL)

请原谅我的无知,这是我第一个处理会话管理的Flask应用程序。上面的代码不断返回RuntimeError: working outside of request context的错误。

这是stacktrace:

Traceback (most recent call last):
  File "runserver.py", line 1, in <module>
    from api import app
  File "/Users/dmonsewicz/dev/autoresponders/api/__init__.py", line 13, in <module>
    import client
  File "/Users/dmonsewicz/dev/autoresponders/api/client/__init__.py", line 33, in <module>
    @blueprint.before_request(load_session_from_cookie())
  File "/Users/dmonsewicz/dev/autoresponders/api/client/__init__.py", line 16, in load_session_from_cookie
    account = check_sso_cookie(request.cookies, for_view=False)
  File "/Users/dmonsewicz/.virtualenvs/autoresponders-api/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/Users/dmonsewicz/.virtualenvs/autoresponders-api/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
    return self.__local()
  File "/Users/dmonsewicz/.virtualenvs/autoresponders-api/lib/python2.7/site-packages/flask/globals.py", line 20, in _lookup_req_object
    raise RuntimeError('working outside of request context')

其他人遇到过这个问题吗?

1 个答案:

答案 0 :(得分:3)

您需要注册函数,而不是函数的返回值:

blueprint.before_request(load_session_from_cookie)

注意,也没有@。这会将函数对象传递给blueprint.before_request()注册方法。

您的版本首先调用了load_session_from_cookie函数,并且加载了模块的时间,还没有请求,因此异常。

@装饰器语法通常在函数定义之前使用,Python会自动为你调用它:

@blueprint.before_request
def load_session_from_cookie():
    # ... your function ...

请注意,这次我们不打电话。

后一种形式是预期的语法,如果你不能在模块加载时应用装饰器,你只需要使用显式形式(第一种)(例如,因为blueprint稍后会动态加载,蓝图工厂功能或类似)。