How to access request in Flask Middleware
It's the application object that constructs the request object: it doesn't exist until the app is called, so there's no way for middleware to look at it beforehand. You can, however, construct your own request object within the middleware (using Werkzeug directly rather than Flask):
from werkzeug.wrappers import Request
req = Request(environ, shallow=True)
You might even be able to construct Flask's own Request object (flask.wrappers.Request
, which is a subclass of Werkzeug's Request class) the same way. Looking at the source I don't see anything that should stop you from doing this, but since it isn't designed to be used that way you're probably best off sticking with the Werkzeug one unless you need one of the extra properties added by Flask's subclass.
Middleware stands between your WSGI server
and Flask Application
. The request
object is created in the Flask Application
. So there isn't any request
object in the middleware.
Perhaps you need a @before_request
handler called just before your view?