Sub topic 8
WSGI and ASGI: how Python apps talk to servers
This chapter explains the two interfaces that let a Python web application and a server work together. It assumes you can read basic Python, know HTTP requests, responses, status codes and headers, and have read the earlier chapters on request flow and the reverse-proxy model.
Why Python needs an interface
PHP-FPM speaks FastCGI and knows how to start PHP scripts. Python has no single built-in equivalent. Many frameworks exist (Django, Flask, FastAPI, Starlette), and many servers exist (Gunicorn, uWSGI, Uvicorn, Hypercorn). Without a shared contract, every framework would need code for every server.
Python solves this with two standard interfaces:
- WSGI (Web Server Gateway Interface) is the synchronous standard, defined in PEP 3333.
- ASGI (Asynchronous Server Gateway Interface) is the successor for asynchronous code. It also supports WebSockets and long-lived connections.
Either interface sits between the application server and your application code. Nginx never talks to your Python code directly. Nginx speaks HTTP to the application server, and the application server speaks WSGI or ASGI to your code.
The WSGI contract
A WSGI application is any callable that accepts two arguments and returns an iterable of bytes. The server calls it once per request.
def application(environ, start_response):
body = b"Hello from WSGI\n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(body))),
])
return [body]Each part has a job:
environis a dictionary describing the request. It holds CGI-style keys such asREQUEST_METHOD,PATH_INFO,QUERY_STRINGandCONTENT_TYPE. Request headers appear asHTTP_keys, soUser-AgentbecomesHTTP_USER_AGENT. The request body is a file-like object underwsgi.input.start_responseis a callable the application uses to set the status line and the response headers.- The return value is an iterable of
bytes. The server sends each chunk to the client in order.
Notice that the application returns bytes, not strings. Returning str is a common error and produces a server error.
What WSGI does and does not do
WSGI handles one request at a time per worker. While your code waits on a database or an external API, that worker does nothing else. This is simple and predictable, and it is why you run several workers. The earlier chapters on process models explain the same idea for PHP-FPM.
WSGI cannot represent a WebSocket or a connection that stays open for minutes. The request-response shape is fixed.
Frameworks hide the callable
You rarely write application(environ, start_response) yourself. Frameworks provide it:
- In Flask, the
Flaskobject is a WSGI callable. If your fileapp.pycontainsapp = Flask(__name__), the target isapp:app. - In Django,
myproject/wsgi.pydefines a variable namedapplication. The target ismyproject.wsgi:application.
The target format is module:callable. Gunicorn imports the module and looks up the name after the colon. A wrong module path or a wrong name is the most common reason Gunicorn fails to start.
The ASGI contract
An ASGI application is an async callable with three arguments:
async def application(scope, receive, send):
if scope["type"] != "http":
return
body = b"Hello from ASGI\n"
await send({
"type": "http.response.start",
"status": 200,
"headers": [
(b"content-type", b"text/plain"),
(b"content-length", str(len(body)).encode()),
],
})
await send({
"type": "http.response.body",
"body": body,
})The three arguments work like this:
scopeis a dictionary describing the connection. Itstypekey ishttp,websocketorlifespan.receiveis an awaitable that returns incoming events, such as chunks of a request body.sendis an awaitable the application calls to emit events, such as the response start and body.
Two differences from WSGI matter in practice. First, the application sends the response as events, so it can send in parts and keep a connection open. Second, header names and values are bytes, and header names are lowercase.
ASGI also defines a lifespan scope. The server uses it to tell the application when it starts and stops, so the application can open and close resources such as database pools.
WSGI compared with ASGI
| Property | WSGI | ASGI |
|---|---|---|
| Call style | Synchronous function call | Asynchronous coroutine |
| Per-request model | Request in, response out | Stream of events |
| WebSockets | Not supported | Supported |
| Long-lived connections | Poor fit | Designed for them |
| Typical frameworks | Flask, Django | FastAPI, Starlette, Django (async mode) |
| Typical servers | Gunicorn, uWSGI, mod_wsgi | Uvicorn, Hypercorn, Daphne |
ASGI is not automatically faster. Asynchronous code helps when the application spends most of its time waiting on network calls. It gives no benefit for code that is CPU-bound, and blocking calls inside an async function stall the whole event loop.
Running each kind under Gunicorn
Gunicorn is a WSGI server. Test the callable directly before putting Nginx in front of it:
gunicorn --workers 3 --bind 127.0.0.1:8000 app:application
curl -i http://127.0.0.1:8000/Gunicorn does not run ASGI applications by itself. The usual pattern is to keep Gunicorn as the process manager and use Uvicorn's worker class:
pip install gunicorn uvicorn
gunicorn --workers 3 --worker-class uvicorn.workers.UvicornWorker --bind 127.0.0.1:8000 app:applicationGunicorn manages the worker processes, restarts crashed ones and handles signals. Each Uvicorn worker runs an event loop that serves ASGI. Recent Uvicorn releases also manage multiple workers themselves with uvicorn --workers, so either arrangement is valid. Under systemd, the first is common because Gunicorn's process management is mature and widely documented.
Where Nginx fits
Nginx does not know whether the backend is WSGI or ASGI. It sees an HTTP server on a socket. The proxy_pass configuration is the same for both:
server {
listen 80;
server_name example.com;
location /static/ {
alias /srv/myapp/static/;
}
location / {
proxy_pass http://unix:/run/gunicorn/app.sock;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}WebSockets need extra configuration, because the proxy must pass the HTTP upgrade handshake. Add these lines to the location that handles WebSocket traffic:
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";Without them, Nginx downgrades the connection and the WebSocket handshake fails.
Common errors
ModuleNotFoundErrorat startup. Gunicorn runs in the directory set byWorkingDirectoryand the virtual environment you named inExecStart. Check both, and check that the module path inmodule:callableis correct.Failed to find attribute 'application'. The name after the colon does not exist in that module. Flask users often useapp, notapplication.- A coroutine was never awaited, or a plain-text error from the server. You started an ASGI application with a plain WSGI server, or the reverse. Match the framework to the server.
- 502 Bad Gateway. Nginx cannot reach the socket. The application server may be stopped, the socket path may differ between the Nginx and Gunicorn configuration, or the Nginx user may lack permission on the socket.
- Wrong scheme in generated URLs. The application sees plain HTTP from Nginx. Pass
X-Forwarded-Protoand tell the framework to trust it, for example with Gunicorn's--forwarded-allow-ipsoption or the framework's own proxy setting.
Choosing between them
Use WSGI when your application is synchronous, your framework is Flask or classic Django, and you do not need WebSockets. It is the simplest option to operate.
Use ASGI when you need WebSockets, server-sent events, or many concurrent connections that mostly wait on I/O, or when your framework (FastAPI, Starlette) is ASGI-only.
You can run a WSGI application inside an ASGI server through an adapter, but doing so gives no async benefit. Match the interface to the framework.
Exercise
A Django project has a file myproject/wsgi.py that defines a variable named application. Write the Gunicorn command that serves it with three workers on the Unix socket /run/gunicorn/app.sock. Then say what you would change if the project used myproject/asgi.py and needed WebSockets.
Show answer
The WSGI command is: gunicorn --workers 3 --bind unix:/run/gunicorn/app.sock myproject.wsgi:application. For ASGI, change the target to myproject.asgi:application and add --worker-class uvicorn.workers.UvicornWorker. Also add the Upgrade and Connection headers, with proxyhttpversion 1.1, to the Nginx location that handles WebSocket traffic.
Exercise
Gunicorn starts without errors, but a request for a page returns 502 Bad Gateway from Nginx. The error log says "connect() to unix:/run/gunicorn/app.sock failed (2: No such file or directory)". Name two likely causes and one command that checks each.
Show answer
Cause 1: the Gunicorn service is not running, so no socket exists. Check with systemctl status gunicorn. Cause 2: Gunicorn binds to a different socket path than the one in proxy_pass. Check with ls -l /run/gunicorn/ and compare the path with the --bind option in the unit file. A third possibility is that RuntimeDirectory is missing from the unit, so /run/gunicorn is never created.