Python3 CGI编程

How CGI worked, why nobody uses it in production, and what replaced it.

Advanced
Key PointsCGI starts a new process per request — that is why it is dead; the cgi module was removed in Python 3.13, use WSGI/ASGI instead.

How CGI Worked

The web server forked a new Python process for every request, passed the request in environment variables and stdin, and read the response from stdout. Simple to implement, ruinous at scale.

Python
#!/usr/bin/env python3
# legacy CGI script: the server runs this once per request
import os
import sys

length = int(os.environ.get("CONTENT_LENGTH") or 0)
body = sys.stdin.read(length)

print("Content-Type: text/plain; charset=utf-8")
print()
print(f"method={os.environ.get('REQUEST_METHOD')} body={body}")

Why It Died

ProblemImpact
Process per request~10-50 ms startup each time
No connection reuseDatabase connections opened per request
No in-process stateNo caches, no pools, no sessions
Hard to deployCGI directory permissions, shebang perms

What Replaced It

  • WSGI (PEP 3333): a long-lived process handles many requests — Flask, Django.
  • ASGI: the async successor — FastAPI, Starlette.
  • FastCGI / uWSGI: persistent processes behind nginx.
import cgi fails on Python 3.13+. If you maintain legacy code, migrate to WSGI — there is no drop-in replacement for the cgi module.

Friends & Partners