中间件内的 Flask 会话

Hyu*_*ang 8 python session middleware flask

有没有办法在中间件中使用 Flask 会话?(烧瓶1.1.1)

我需要在应用程序请求之前访问会话以获取“user_id”。

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'

Run Code Online (Sandbox Code Playgroud)

提前致谢。