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.
Use a Flask Request Context in Your Middleware
If you really need to access session data in middleware, you must create a request context manually. However, this requires you to have a reference to the actual Flask app instance (not just the WSGI app). For example:
from flask import session
class Middleware(object):
def __init__(self, wsgi_app, flask_app):
self.wsgi_app = wsgi_app
self.flask_app = flask_app # This must be the Flask app instance
def __call__(self, environ, start_response):
with self.flask_app.request_context(environ):
user_id = session.get('user_id')
print("User ID:", user_id)
return self.wsgi_app(environ, start_response)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With