On this page
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
wsgiref.simple_serveris single-threaded and dev-only: Use Gunicorn/uWSGI (or an ASGI server for async apps) in production.- Response iterables must yield
bytes, neverstr: Wrap withwsgiref.validate.validator(app)in tests to catch PEP 3333 violations early. - WSGI is synchronous: For WebSockets or async streaming, use ASGI instead.
Linked from
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/winsound Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/xml Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/base64 Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/email Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/json Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/mailbox Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/mimetypes Linked here; shared tags: #stdlib
- tuts/python3/tutorials/popular_application_domains/web_development_and_apis links to this page; shared tags: #stdlib