dennismonsewicz
dennismonsewicz

Reputation: 25542

Flask: before_request to check session and/or cookie not working

Here is my code:

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)

Excuse my ignorance, this is my first Flask app that deals with session management. The above code keeps returning the error of RuntimeError: working outside of request context.

Here is the 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')

Anyone else run into this issue?

Upvotes: 1

Views: 3567

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122372

You need to register the function, not the return value of the function:

blueprint.before_request(load_session_from_cookie)

Note, no @ either. This passes the function object to the blueprint.before_request() registration method.

Your version instead first called the load_session_from_cookie function, and the time your module is loaded, there is no request yet, hence the exception.

The @ decorator syntax is normally used before the function definition, and Python will automatically call it for you:

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

Note that this time we don't call it.

The latter form is the intended syntax, you only need to use the explicit form (the first) if you cannot apply the decorator at module load time (say, because blueprint is loaded dynamically later on, in a blueprint factory function or similar).

Upvotes: 3

Related Questions