WSGI Fallback Middleware
Relevant source files
The following files were used as context for generating this wiki page:
The WSGI Fallback Middleware in Uvicorn provides a compatibility layer that allows synchronous Web Server Gateway Interface (WSGI) applications to run within the asynchronous Asynchronous Server Gateway Interface (ASGI) environment. This middleware is essential for users transitioning from legacy synchronous frameworks to async-first servers like Uvicorn, as it handles the translation between ASGI scopes/events and the WSGI environ/start_response patterns.
Uvicorn historically implemented a native _WSGIMiddleware. However, this native implementation is now deprecated in favor of the external a2wsgi library. The middleware serves as a bridge, running the WSGI application in a separate thread pool to prevent blocking the asynchronous event loop.
Sources: uvicorn/middleware/wsgi.py:114-118, README.md:83-93, CHANGELOG.md:377-380
Architecture and Components
The system architecture consists of a wrapper that intercepts ASGI calls and delegates the actual processing to a specialized responder that manages threading.
_WSGIMiddleware
This class is the entry point for WSGI-to-ASGI translation. It initializes a ThreadPoolExecutor to handle the synchronous nature of WSGI applications. When called, it validates that the ASGI scope type is http and then instantiates a WSGIResponder.
Sources: uvicorn/middleware/wsgi.py:113-131
WSGIResponder
The WSGIResponder manages the lifecycle of a single request. It is responsible for:
- Accumulating the ASGI request body.
- Building the WSGI
environdictionary. - Running the WSGI application in an executor.
- Capturing the WSGI response via a
start_responsecallback and an iterable return value. - Streaming the response back to the client using ASGI
sendevents.
Sources: uvicorn/middleware/wsgi.py:134-210
Dependency Selection Logic
Uvicorn attempts to use a2wsgi if installed. If not, it falls back to its internal (deprecated) implementation.
try:
from a2wsgi import WSGIMiddleware
except ModuleNotFoundError:
WSGIMiddleware = _WSGIMiddleware
Sources: uvicorn/middleware/wsgi.py:213-216
Data Flow: Request and Response
The data flow involves translating asynchronous ASGI events into a synchronous WSGI environment and back again.
Request Transformation
The middleware first reads the entire request body from the ASGI receive callable. This is necessary because WSGI expects a synchronous stream (wsgi.input) rather than asynchronous chunks. Once accumulated, the build_environ function converts the HTTPScope and request data into a standard WSGI dictionary.
Sources: uvicorn/middleware/wsgi.py:155-167, uvicorn/middleware/wsgi.py:30-80
Environ Mapping
The following table describes how ASGI scope fields are mapped to WSGI environment variables:
| WSGI Variable | Derived From | Description |
|---|---|---|
REQUEST_METHOD | scope["method"] | HTTP Method (GET, POST, etc.) |
SCRIPT_NAME | scope.get("root_path") | The initial portion of the request path |
PATH_INFO | scope["path"] | The remaining portion of the request path |
QUERY_STRING | scope["query_string"] | The URL query string |
SERVER_PROTOCOL | scope["http_version"] | Usually HTTP/1.1 |
REMOTE_ADDR | scope.get("client") | Client's IP address |
wsgi.input | Accumulated body | A BytesIO object containing the request body |
Sources: uvicorn/middleware/wsgi.py:34-78, uvicorn/_types.py:65-79
Execution Flow
The following diagram illustrates the interaction between the ASGI server, the Middleware, and the synchronous WSGI application.
The WSGIResponder uses an asyncio.Event named send_event and a deque named send_queue to safely pass response data from the synchronous worker thread back to the asynchronous sender task.
Sources: uvicorn/middleware/wsgi.py:168-185, uvicorn/middleware/wsgi.py:187-210
Key Implementation Details
Exception Handling
If the WSGI application provides exc_info during the start_response call, the middleware stores it. If an exception occurs during the synchronous execution, the WSGIResponder re-raises the exception in the main asynchronous loop after the executor task completes.
Sources: uvicorn/middleware/wsgi.py:175-185, uvicorn/middleware/wsgi.py:192-193
Header Processing
Headers are converted from ASGI's list of byte tuples to WSGI's HTTP_ prefixed environment variables. Special handling is provided for Content-Length and Content-Type, which are mapped directly to CONTENT_LENGTH and CONTENT_TYPE without the HTTP_ prefix. If multiple headers with the same name exist, their values are joined with commas.
Sources: uvicorn/middleware/wsgi.py:61-78
Performance Considerations
The WSGIResponder accumulates the request body into a io.BytesIO object. In tests, it is demonstrated that it can handle large bodies via fragmented http.request events. However, because the entire body is read into memory before the WSGI app starts, this can be memory-intensive for very large uploads.
Sources: uvicorn/middleware/wsgi.py:157-167, tests/middleware/test_wsgi.py:82-91
Conclusion
The WSGI Fallback Middleware acts as a robust bridge between the legacy synchronous world of WSGI and the modern asynchronous world of ASGI. By leveraging thread pools and careful environ mapping, it allows Uvicorn to serve a wide variety of Python web applications, even those not yet updated for async concurrency. While the native implementation is deprecated, its logic remains a reference for how Uvicorn maintains backward compatibility.
Sources: uvicorn/middleware/wsgi.py:114-118, README.md:83-93