On this page
  1. wsgiref
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Serving a Local WSGI App with make_server
  7. Gotchas & Boundaries

wsgiref

Prev: winsound | Up: stdlib_module | Next: xml
Rel: email, json, mailbox, mimetypes, base64
Ref: docs.python.org — wsgiref
Tags: #public #python3 #stdlib


Import

import wsgiref

Overview

Reference implementation of Python's WSGI (PEP 3333) synchronous web server/application interface (wsgiref.simple_server, wsgiref.validate, wsgiref.headers, wsgiref.util). Useful for zero-dependency local web tools, WSGI middleware validation, and writing HTTP test servers without third-party frameworks.

Quick Start

from wsgiref.validate import validator

def app(environ, start_response):
    body = b"hello wsgi\n"
    start_response("200 OK", [("Content-Type", "text/plain; charset=utf-8"), ("Content-Length", str(len(body)))])
    return [body]

checked_app = validator(app)
assert callable(checked_app)

Implementation Walkthrough

1. Serving a Local WSGI App with make_server

from wsgiref.simple_server import make_server

def health_app(environ, start_response):
    path = environ.get("PATH_INFO", "/")
    status = "200 OK" if path == "/health" else "404 Not Found"
    body = b'{"ok":true}' if status.startswith("200") else b'{"ok":false}'
    start_response(status, [("Content-Type", "application/json"), ("Content-Length", str(len(body)))])
    return [body]

# with make_server("127.0.0.1", 8000, health_app) as httpd:
#     httpd.serve_forever()

Gotchas & Boundaries

Linked from

Related notes