Running a WSGI app

aiohttp_wsgi allows you to run WSGI applications (e.g. Django, Flask) on aiohttp. This allows you to add async features like websockets and long-polling to an existing Python web app.

Hint

If you don’t need to add websockets or async request handlers to your app, but still want to run your WSGI app on the asyncio event loop, aiohttp_wsgi provides a simpler command line interface.

Run a simple web server

In order to implement a WSGI server, first import your WSGI application and wrap it in a WSGIHandler.

from aiohttp import web
from aiohttp_wsgi import WSGIHandler
from your_project.wsgi import application

wsgi_handler = WSGIHandler(application)

Next, create an Application instance and register the request handler with the application’s router on a particular HTTP method and path:

app = web.Application()
app.router.add_route("*", "/{path_info:.*}", wsgi_handler)

After that, run the application by run_app() call:

web.run_app(app)

See the aiohttp.web documentation for information on adding websockets and async request handlers to your app.

Extra environ keys

aiohttp_wsgi adds the following additional keys to the WSGI environ:

asyncio.loop
The EventLoop running the server.
asyncio.executor
The Executor running the WSGI request.
aiohttp.request
The raw aiohttp.web.Request that initiated the WSGI request. Use this to access additional request metadata.

API reference

class aiohttp_wsgi.WSGIHandler(application, *, url_scheme=None, stderr=None, inbuf_overflow=524288, max_request_body_size=1073741824, executor=None, loop=None)

An adapter for WSGI applications, allowing them to run on aiohttp.

Parameters:
  • application (callable) – A WSGI application callable.
  • url_scheme (str) – A hint about the URL scheme used to access the application. Corresponds to environ['wsgi.url_scheme']. Default is auto-detected to 'http' or 'https'.
  • stderr (io.BytesIO) – A file-like value for WSGI error logging. Corresponds to environ['wsgi.errors']. Defaults to sys.stderr.
  • inbuf_overflow (int) – A tempfile will be created if the request body is larger than this value, which is measured in bytes. Defaults to 524288.
  • max_request_body_size (int) – Maximum number of bytes in request body. Defaults to 1073741824. Larger requests will receive a HTTP 413 (Request Entity Too Large) response.
  • executor (concurrent.futures.Executor) – An Executor instance used to run WSGI requests. Defaults to the asyncio base executor.
  • loop (asyncio.BaseEventLoop) – The asyncio loop. Defaults to asyncio.get_event_loop().