WSGI / ASGI
WSGI is the synchronous Python web server contract: a callable app(environ, start_response). ASGI is the asynchronous successor: an async callable that handles HTTP, WebSockets, and lifespan over a connection scope.
Detailed Explanation
A production Flask or Django (WSGI) process is not the framework talking to the network. Gunicorn, uWSGI, or mod_wsgi import your application callable and call it once per request, in a worker thread or process. environ is a dict of CGI-like keys. start_response(status, headers) begins the response; the callable returns an iterable of body bytes. That is WSGI (PEP 3333). It is simple and blocking. One request occupies one worker until it finishes.
ASGI (Starlette, FastAPI, Django ASGI) receives a scope dict, an async receive, and an async send. The server (uvicorn, daphne, hypercorn) multiplexes many connections on an event loop. HTTP is one protocol in the scope. WebSockets and lifespan (startup/shutdown) are others. A FastAPI app is an ASGI app. You can mount WSGI apps inside ASGI with adapters, with the expected threadpool cost.
Choose WSGI when the stack is sync and you scale with processes (classic Django + gunicorn). Choose ASGI when you need WebSockets, long-lived connections, or a lot of concurrent I/O on one process. Running a sync ORM in an ASGI view without care blocks the loop and throws away the advantage.
Both contracts keep the server replaceable. Do not call socket.listen inside the framework. Do not assume the number of workers. Store shared state in a database or cache, not in a module-level dict, unless you accept per-process memory.
environ["PATH_INFO"] vs scope["path"] is the same idea in two shapes. Middleware is a wrapper around the callable. WSGI middleware is a class; ASGI middleware is usually a Starlette-style wrapper.
Code Examples
def wsgi_app(environ, start_response):
body = b"ok\n"
start_response("200 OK", [("Content-Type", "text/plain")])
return [body]async def asgi_app(scope, receive, send):
if scope["type"] != "http":
return
await send({
"type": "http.response.start",
"status": 200,
"headers": [(b"content-type", b"text/plain")],
})
await send({"type": "http.response.body", "body": b"ok\n"})Common Gotchas
Running an ASGI app on a WSGI-only server
uvicorn speaks ASGI. gunicorn needs an ASGI worker (`uvicorn.workers.UvicornWorker`) for FastAPI.
Blocking I/O in an ASGI handler
the loop freezes. Use async drivers or a threadpool.
In-memory state on the app object
extra workers do not share it. Use Redis or a database.
`start_response` must be called before you iterate the body
a generator that writes first is illegal WSGI.