How to access request in Flask Middleware
Asked Answered
L

3

14

I want to access request.url in middleware.

Flask app - 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 request can be accessed in Flask application context. We normally use

with app.test_request_context()

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

How do I proceed?

Thanks for any help..

Laurasia answered 2/9, 2013 at 12:48 Comment(1)
Just pass the app object to the middleware and you'll have access to it: app.wsgi_app = TestMiddleware(app.wsgi_app, app)Sandstone
O
15

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.

Outlook answered 2/9, 2013 at 13:38 Comment(1)
Using res might then lead to exhaustion of some streams. See https://mcmap.net/q/829160/-changing-request-method-using-hidden-field-_method-in-flaskBeaded
J
9

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?

Jesu answered 2/9, 2013 at 13:32 Comment(0)
S
0

You can't have a Request object before the application finds an URL rule and creates it. However, after the application has done its thing, you can find the Request object in the environ:

environ['werkzeug.request']
Sanative answered 28/1, 2020 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.