Wim Onderbeke

What's WSGI anyway

A brief overview of WSGI in Python

  ·   2 min read

Python web frameworks are not full-fledged web servers on their own. While they often include a lightweight development server for local use, they make it clear that this should not be used in production. These built-in servers typically lack support for TLS certificates and aren’t optimized for serving static content, among other limitations. That’s why web frameworks are commonly used alongside battle-tested web servers that handle connection management and offer robust features for scaling and securing web applications. However, these web servers and frameworks need a way to communicate—enter WSGI, the Web Server Gateway Interface, as described in PEP 333.

Instead of each web server and web framework offering their own interfaces to communicate with each other, PEP 333 proposes a simple interface between them. When looking in the source code of your Python web framework of choice, you’ll find that exact interface implemented in all of them. A callable object that takes in two positional arguments, canonically named environ and start_response:

def application(environ, start_response): ...

Here’s a simple example implementation of this interface:

def application(environ, start_response):
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    return [b'Hello world!\n']

You can invoke the start_response callback with the status and headers you want to send back, and send back your response body by simply returning it. The environ object is a dictionary containing information about the incoming HTTP request, such as the request method, path, and server protocol:

{
    'REQUEST_METHOD': 'GET',
    'PATH_INFO': '/hello',
    'CONTENT_TYPE': 'text/plain',
    ...
}

When your web framework implements this interface, it can be used together with any web server that can call it. That’s all there is to WSGI, a specification that successfully brought some standardization to the zoo of existing web technologies in Python. In later posts, we’ll also dive deeper into the inner workings of WSGI servers such as gunicorn.