Application

The WGSI server must be passed an application to run. The application’s interface is implemented as a callable such as a function, a method, a class, or an instance. That callable must:

  1. Accept two positional parameters:

    • A dictionary containing environment variables.

    • A callback function used by the application to send the HTTP status code/message and HTTP headers to the server.

  2. Return the response body to the server as an iterable of bytes.

Environment Dictionary

The environment dictionary is populated by the server for every client request. It contains key-value pairs such as:

HTTP_ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_ENCODING: gzip, deflate, br, zstd
HTTP_ACCEPT_LANGUAGE: en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7
HTTP_CONNECTION: keep-alive
HTTP_DNT: 1
HTTP_HOST: localhost:8051

Python WSGI server

Python includes a bundled WSGI wsgiref.simple_server. The wsgiref.simple_server.make_server constructor is passed an application callable which is responsible for handling requests and generating responses. Within:

To start the server, include the following logic in a Python script:

from wsgiref.simple_server import make_server

# Instantiate the server
httpd = make_server (
   'localhost', # The host name
   8051, # A port number where to wait for the request
   application # The application object name, in this case a function
)

# Wait for a single request, serve it and quit
httpd.handle_request()

The scripts in this tutorial were tested on a Fedora Linux system. They will likely run without issue on any modern Linux distribution as well as on Windows with minor adjustments.

Note

On Windows, it may be necessary to add the path to python.exe to the system environment PATH variable. Furthermore if you have the option use Linux instead of Windows it is highly recommended; it will save you a considerable amount of trouble.