skip to content

How do you serve a legacy Flask app under /legacy inside a FastAPI 0.143 app, and what does that mounted WSGI app miss?

level: middleimportance: should knowfreq 20%

answer

  1. WSGI inside an ASGI app
  2. an adapter package, not fastapi.middleware
  3. SCRIPT_NAME carries the prefix
  4. a thread pool per wrapper
  5. outside the schema and the dependencies

basics

~20 s

In FastAPI 0.143, wrap the Flask app in a2wsgi's WSGIMiddleware and mount it with app.mount("/legacy", ...). Flask runs in a2wsgi's thread pool, outside FastAPI's schema, dependencies and exception handlers; only the main app's middleware still wraps it.

solid answer

~40 s

Flask speaks WSGI and FastAPI speaks ASGI, so the Flask app is wrapped in an adapter and mounted: `app.mount("/legacy", WSGIMiddleware(flask_app))` with `WSGIMiddleware` imported from `a2wsgi`. In FastAPI 0.143, `fastapi.middleware.wsgi` only re-exports Starlette's `WSGIMiddleware`, which Starlette deprecates and which warns on import. Flask receives `SCRIPT_NAME=/legacy` and the rest of the path in `PATH_INFO`, so its routes keep their old paths and its generated links include `/legacy`. a2wsgi runs each WSGI call in its own thread pool, `workers=10` by default, so blocking Flask code does not stall the event loop but its concurrency is capped. Being a mount, the Flask app is absent from FastAPI's schema and docs and skips FastAPI's dependencies, validation and exception handlers; its own auth must stay. The main app's middleware still wraps it.

code

python · 19 lines
python
from a2wsgi import WSGIMiddleware
from fastapi import FastAPI


def legacy_app(environ, start_response):
    body = f"SCRIPT_NAME={environ['SCRIPT_NAME']} PATH_INFO={environ['PATH_INFO']}"
    start_response("200 OK", [("Content-Type", "text/plain")])
    return [body.encode()]


app = FastAPI()


@app.get("/api/health")
async def health() -> dict[str, bool]:
    return {"ok": True}


app.mount("/legacy", WSGIMiddleware(legacy_app))

go deeper

for a junior

Recall the recipe: wrap the Flask app in WSGIMiddleware from a2wsgi and mount it at a prefix with app.mount().

for a middle

Explain how SCRIPT_NAME and PATH_INFO split the path, that a2wsgi runs WSGI calls in a thread pool of ten workers by default, and why fastapi.middleware.wsgi is deprecated.

for a senior

Name what the mount loses, schema, dependencies, validation and handlers, and make sure the legacy routes keep their own authentication while the main middleware still wraps them.

for a principal

Plan the strangler migration: which routes move first, how long the legacy mount may live, and when one process hosting both stacks costs more than splitting them at the proxy.

## Why a legacy app needs an adapter **WSGI** is Python's synchronous server interface: a WSGI app is a callable that receives an `environ` dictionary and a `start_response` function and returns the body. Flask and Django are WSGI frameworks. **ASGI** is the asynchronous interface FastAPI and Starlette implement. An ASGI app cannot call a WSGI app directly, so the WSGI app is wrapped in an **adapter** that turns each ASGI request into a WSGI call, runs it, and streams the result back. This is a common step in a gradual migration: new endpoints are written in FastAPI, while the old Flask app keeps answering its existing URLs under a prefix such as `/legacy` until each of them is rewritten. ## The 0.143 recipe 1. Add the `a2wsgi` package to the project. 2. Import `WSGIMiddleware` from `a2wsgi`. 3. Mount the wrapped app: `app.mount("/legacy", WSGIMiddleware(flask_app))`. FastAPI's docs used to import `WSGIMiddleware` from `fastapi.middleware.wsgi`. In 0.143 that module only re-exports Starlette's `WSGIMiddleware`, and Starlette 1.7 marks `starlette.middleware.wsgi` deprecated: importing it emits a `StarletteDeprecationWarning` pointing to a2wsgi. The docs switched to a2wsgi in 0.128.1 and say the usage stays the same. ## What the Flask app sees - **Path split.** For `GET /legacy/orders/7`, a2wsgi builds the WSGI `environ` with `SCRIPT_NAME` set to `/legacy` (the mount path, which the mount passes as the ASGI `root_path`) and `PATH_INFO` set to `/orders/7`. A Flask route declared as `/orders/<int:order_id>` keeps working unchanged, and links Flask generates include the `/legacy` prefix. - **Trailing slash.** A request for `/legacy` exactly is redirected with `307` to `/legacy/`, because the mount matches paths below its prefix. - **Threads.** a2wsgi's `WSGIMiddleware(app, workers=10, send_queue_size=10)` creates its own `ThreadPoolExecutor` with `max_workers=workers`. Each request runs the WSGI callable in one of those threads, so blocking Flask code does not block the event loop, but no more than `workers` legacy requests run at once per wrapper; the rest wait. - **Headers and body.** Request headers arrive as the usual `HTTP_*` keys (with `CONTENT_TYPE` and `CONTENT_LENGTH` unprefixed), the query string as `QUERY_STRING`, and the body through `wsgi.input`, so Flask's `request` object works as before. - **No WebSockets.** a2wsgi closes a WebSocket connection sent to a WSGI app, since WSGI has no way to handle one. - **The original request is reachable.** a2wsgi also puts the ASGI scope in the environ under `asgi.scope`, which helps when legacy code needs a value only the ASGI side has. ## What the mounted app does not get A mount is an independent application, and a WSGI one more so. | FastAPI feature | Applies to the mounted Flask app? | |---|---| | OpenAPI schema and `/docs` | no: its routes are not documented | | App-wide `FastAPI(dependencies=...)`, router dependencies | no | | FastAPI's request validation and `422` responses | no | | FastAPI exception handlers | no: Flask's own error handling applies | | Middleware added to the main FastAPI app | yes, as the outer layer | The security consequence is the one to check in review: an authentication dependency on the FastAPI app does **not** protect `/legacy/...`. Flask's own login checks must stay in place until each route has moved, or the protection has to live in middleware on the main app, which does wrap the mount. ## Operating it - **Size the pool deliberately.** If legacy routes are slow, `workers=10` can become the bottleneck for `/legacy` while FastAPI routes stay fast; raise it with care, since every thread shares the one process. - **Errors are Flask's.** A Flask exception produces whatever Flask's error handling returns, not FastAPI's error body, so clients of `/legacy` keep the old error format. - **Mount order.** A mount is matched in declaration order like any route, so mount the legacy app at a prefix no FastAPI route uses. - **Retire it route by route.** Move one legacy URL at a time into FastAPI routes outside the `/legacy` prefix, then delete the mount when nothing is left. Django works the same way: wrap the WSGI application object its `wsgi.py` module exposes with a2wsgi's `WSGIMiddleware` and mount it. It then also receives `/legacy` in `SCRIPT_NAME`, so its URL patterns keep their existing paths, and the same limits apply: its own errors, its own authentication, no place in FastAPI's schema, and a capped thread pool.

  • In a FastAPI app with a Flask app mounted through a2wsgi, legacy requests queue up under load while FastAPI routes stay fast. Why?
    a2wsgi's `WSGIMiddleware` runs WSGI calls in its own `ThreadPoolExecutor`, sized by `workers`, 10 by default. When slow legacy requests occupy all ten threads, further `/legacy` requests wait for a free thread, while FastAPI's own routes run on the event loop and are unaffected. Raise `workers` if the process can afford it, or speed up or move the slow routes.
  • In FastAPI 0.143, what happens if you keep importing WSGIMiddleware from fastapi.middleware.wsgi?
    It still works today, because the module re-exports Starlette's `WSGIMiddleware`, but importing it emits a `StarletteDeprecationWarning` saying the module will be removed in a future release and pointing to a2wsgi. Switch the import to `from a2wsgi import WSGIMiddleware`; the mount call stays the same.

  • fastapi.middleware.wsgi is the recommended import in FastAPI 0.143
  • A FastAPI auth dependency also protects the mounted Flask routes
  • Flask sees the full /legacy/... path and its routes must be renamed
  • The mounted WSGI app blocks the event loop on every request
  • Mounted Flask routes appear in FastAPI's /docs

Assumes FastAPI 0.143 on Starlette 1.7, where fastapi.middleware.wsgi re-exports Starlette's deprecated WSGIMiddleware and the docs recommend a2wsgi.