Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 72 ยท Structure and Configuration

WSGI Middleware in Flask

Wrap a Flask app in WSGI middleware. Write a timing middleware class, fix client IPs with ProxyFix, mount apps with DispatcherMiddleware, and learn when to use Flask hooks instead.

A Flask app is a WSGI application: a callable that receives the request as a dictionary (environ) and a function (start_response), and returns the response body. Because that interface is so small, anything that speaks it can be put around your app. That wrapper is called WSGI middleware. It sees every request before Flask does and every response after Flask produced it, regardless of which route runs.

You have already met one middleware, ProxyFix, in Deploying Flask. In this lesson you will understand how middleware works, write your own, and learn two more built-in ones from Werkzeug. You will also learn when not to use middleware, because Flask's own hooks are often the better tool.

Where middleware sits

flowchart LR
    S["WSGI server<br/>(gunicorn)"] --> M1["Middleware A"]
    M1 --> M2["Middleware B"]
    M2 --> F["Flask.wsgi_app<br/>(routing, views, hooks)"]
    F --> M2
    M2 --> M1
    M1 --> S

The request travels inward through each layer; the response travels back out in the opposite order.

When the server calls your app, Flask's __call__ simply calls self.wsgi_app(environ, start_response). That method does the real work: it builds the request context, runs hooks, calls your view and returns the response. Wrapping app.wsgi_app (not app itself) is the officially recommended place, because you keep the Flask object and its url_map, config and extensions intact.

Python
app.wsgi_app = MyMiddleware(app.wsgi_app)

Writing a middleware class

A middleware is any callable with this shape. It receives the next application in its constructor and exposes the same WSGI interface:

Python
class Middleware:
    def __init__(self, app):
        self.app = app                      # the thing we wrap

    def __call__(self, environ, start_response):
        # 1. look at or change environ (the request)
        # 2. call the wrapped app
        # 3. look at or change the response
        return self.app(environ, start_response)

To change the response headers you wrap start_response, because that is the moment the app announces its status and headers.

Python A timing and header middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Even the 404 for /nope carries the headers. That is the main difference from a Flask hook: middleware wraps everything, including requests that never matched a route, errors raised before Flask's own handling and static files.

Middleware can also change the request by editing environ before passing it on. For example, a method-override middleware can read a ?_method=DELETE parameter and set environ["REQUEST_METHOD"], which lets plain HTML forms send verbs they otherwise cannot.

Python Changing the request: method override

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

ProxyFix: trust the proxy, carefully

Behind nginx, a load balancer or Cloudflare, your app sees the proxy's address and plain HTTP. The real client details arrive in headers such as X-Forwarded-For and X-Forwarded-Proto. Werkzeug's ProxyFix rewrites environ from those headers so that request.remote_addr, request.scheme, request.host and url_for(..., _external=True) are correct. The number you give is how many proxies you trust; trusting more than you have lets a client forge its own IP.

Python ProxyFix and the number of trusted proxies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

ProxyFix reads the list from the right, one entry per trusted proxy. With x_for=1 it takes the rightmost value, 10.0.0.2: the address your own proxy says it received the request from. The entries further left (203.0.113.9) are claims made by earlier hops, and a client can forge them, so they are ignored. Set the numbers to match your real infrastructure and leave an argument at 0 for headers your proxy does not set.

DispatcherMiddleware: several apps, one process

werkzeug.middleware.dispatcher.DispatcherMiddleware mounts WSGI apps under URL prefixes. It is useful for gluing independent Flask apps together (a public site and an admin site, an API and its docs), for migrating an old app piece by piece, or for hosting a Flask app under a sub-path.

Python Mounting two apps under prefixes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The mounted app thinks it lives at its own root: url_for('admin_home') in the admin app returns /admin/ because the dispatcher moves the prefix into SCRIPT_NAME. Each app has its own config, extensions and secret key; cookies set by one are sent to the other if their paths overlap, so give them different SESSION_COOKIE_NAME or SESSION_COOKIE_PATH values. For most projects blueprints inside one app are simpler. Reach for DispatcherMiddleware when you genuinely have separate apps.

Order of layers

When you wrap more than once, the last wrapper is the outermost and sees the request first:

Python
app.wsgi_app = Inner(app.wsgi_app)    # closest to Flask
app.wsgi_app = Outer(app.wsgi_app)    # sees the request first, the response last

A common arrangement is ProxyFix outermost (so every inner layer sees the true client address), then logging or timing, then your own checks.

Middleware or Flask hooks?

Use When
before_request / after_request (hooks) You need request, session, g, the logged-in user or the matched endpoint. This is most application logic.
WSGI middleware The behavior must apply to every request, even ones Flask never routes, or it is not Flask-specific (proxy headers, mounting, compression, request IDs, rewriting paths before routing).

Inside middleware there is no Flask request object and no session, only the raw environ. Reading a request body there is also risky: if you consume wsgi.input, Flask can no longer read it.

WSGI and ASGI, and the Falcon framework

Everything on this page assumes WSGI: a synchronous interface where the server calls app(environ, start_response) once per request and waits for the answer. Its younger sibling ASGI is built for async code, long-lived connections such as WebSockets, and many waiting requests per process. The two are not compatible with each other: a WSGI middleware cannot wrap an ASGI app.

WSGI ASGI
Entry point app(environ, start_response) await app(scope, receive, send)
Style one request at a time per worker thread many requests share an event loop
Typical servers gunicorn, uWSGI, Waitress uvicorn, Hypercorn, Daphne
Frameworks Flask, classic Django, Falcon FastAPI, Starlette, Django (async), Falcon

Falcon is a small, performance-oriented framework that deliberately stays close to HTTP: you write a resource class with on_get, on_post and so on, and set the response by hand. It is a good illustration of the difference, because the very same API exists for both interfaces: falcon.App is WSGI and falcon.asgi.App is ASGI, and the resource methods become async def in the second.

Python The same endpoint in Falcon (WSGI and ASGI)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Flask itself stays WSGI. It runs async def views by pushing them onto an event loop for the length of one request (async views), which helps with several slow calls inside one request but is not a full ASGI application. If you need thousands of open connections, choose an ASGI framework such as FastAPI; if you only need to host a Flask app on an ASGI server, wrap it with asgiref.wsgi.WsgiToAsgi(app).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which object should you wrap with middleware in a Flask app?

    Assign app.wsgi_app = Middleware(app.wsgi_app). The Flask object keeps its routing, config and extensions, and still works with app.test_client() and the CLI.
  2. 2. How does a middleware add a header to every response?

    The wrapped app calls start_response(status, headers) when it begins the response. The middleware passes in its own function that adds headers first.
  3. 3. What does ProxyFix(app, x_for=1) mean?

    The number is how many proxies you trust. Trusting more than you actually have lets clients forge their IP address.
  4. 4. When is a Flask before_request hook the better choice than WSGI middleware?

    Hooks run inside the request context, so they can use request, session, g and current_user. Middleware only sees the raw WSGI environ.

Summary

  • WSGI middleware is a callable that wraps another WSGI app; install it with app.wsgi_app = Middleware(app.wsgi_app).
  • It can read or change environ on the way in and wrap start_response to change status and headers on the way out.
  • ProxyFix repairs client IP, scheme and host behind proxies; the numbers must equal the proxies you really trust.
  • DispatcherMiddleware mounts several apps under URL prefixes inside one process.
  • The last wrapper added is the outermost layer.
  • Prefer Flask hooks when you need request, session or g; use middleware for cross-cutting, framework-independent concerns.

Next, split your application into reusable pieces with Blueprints, or revisit the request lifecycle to see exactly where wsgi_app sits.