Environment DictionaryΒΆ

The environment dictionary is populated by the server with CGI like variables at each request from the client. This script will output the whole dictionary:

#! /usr/bin/env python

# Python's bundled WSGI server
from wsgiref.simple_server import make_server

def application (environ, start_response):

    # Sorting and stringifying the environment key, value pairs
    response_body = [
        '%s: %s' % (key, value) for key, value in sorted(environ.items())
    ]
    response_body = '\n'.join(response_body)

    status = '200 OK'
    response_headers = [
        ('Content-Type', 'text/plain'),
        ('Content-Length', str(len(response_body)))
    ]
    start_response(status, response_headers)

    return [response_body]

# 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()

To run this script save it as, say, environment.py, open the terminal, navigate to the directory where it was saved and type python environment.py at the command line. The server will be listening at http://localhost:8051

Note

If in Windows it is necessary first to add the path to python.exe to the system environment Path variable. By the way if you can use Linux in instead of Windows do it. It will save some pain.