How to access a request in Flask MIddleware

I want to access request.url in middleware.

Flask attachment - test.py

from flask import Flask from middleware import TestMiddleware app = Flask(__name__) app.wsgi_app = TestMiddleware(app.wsgi_app) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() 

middleware.py:

 from flask import request class TestMiddleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): # How do I access request object here. print "I'm in middleware" return self.app(environ, start_response) 

I understand that a request may be available in the context of a Flask application. Usually we use

 with app.test_request_context() 

But in middleware, I don't have access to the Flask application object.

How do I proceed?

Thanks for any help ..

+6
source share
2 answers

This is the application object that creates the request object: it does not exist until the application is called, so there is no way for the middleware to view it in advance. However, you can create your own request object in the middleware (using Werkzeug directly, not Flask):

 from werkzeug.wrappers import Request req = Request(environ, shallow=True) 

You might even be able to construct your own Flask request object ( flask.wrappers.Request , which is a subclass of the Werkzeug Request class). Looking at the source , I don’t see anything that should stop you from doing this, but since it is not intended to be used in this way, you are probably best off sticking with Werkzeug unless you need one of the additional properties added by the Flask subclass.

+8
source

Middleware stands between your WSGI server and Flask Application . The request object is created in Flask Application . Thus, there is no request object in middleware.

Perhaps you need a @before_request handler that @before_request called just before your view?

+3
source

Source: https://habr.com/ru/post/952976/


All Articles