Flask session inside middleware

Viewed 475

Is there any way to use flask session inside middleware? (flask 1.1.1)

I need to access session to get "user_id" before app request.

from flask import session

class Middleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        1)
        print(session['user_id'])  # RuntimeError: Working outside of request context.

        2)
        with self.app.app_context():  # AttributeError: 'function' object has no attribute 'app_context'
            print(session['user_id'])

        3)
        with self.app(environ, start_response).app_context():  
            # AttributeError: 'ClosingIterator' object has no attribute 'app_context'

Thanks in advance.

0 Answers
Related