The aiohttp library in Python provides great support for asynchronous HTTP handling. However, many Python web applications are written using the WSGI standard interface. Thankfully, aiohttp provides a way to run WSGI apps directly, making it easy to leverage aiohttp's performance while still supporting existing WSGI apps.
Why Run WSGI in aiohttp?
There are a few key reasons you may want to run WSGI apps with aiohttp:
How the aiohttp WSGI Hosting Works
Under the hood, aiohttp implements a WSGI handler using a threadpool. Each WSGI request is handled in a separate thread using a thread pool executor. This allows the WSGI app to perform blocking I/O without impacting overall server performance.
Here is a simple example:
from aiohttp import web
import aiohttp_wsgi
def wsgi_app(environ, start_response):
#...
start_response('200 OK', [('Content-Type', 'text/plain')])
return [b'Hello World']
app = web.Application()
app.router.add_route("*", "/{path_info:.*}", aiohttp_wsgi.WSGIHandler(wsgi_app))
web.run_app(app)
This mounts the WSGI app at the path
Considerations for WSGI in aiohttp
There are a few things to keep in mind:
Overall though, for many workloads hosting WSGI in aiohttp provides an excellent performance boost. Care should be taken with expensive blocking I/O calls inside WSGI apps.