WSGI (Web Server Gateway Interface) 是 Python Web 應用與伺服器溝通的標準介面 (PEP 3333)。本文從 HTTP 協議本質切入,詳細解析 WSGI 介面定義、application 可呼叫物件、environ 與 start_response 參數、內建 wsgiref 伺服器測試,並引導進入 Web 框架抽象層。
瀏覽器 → HTTP 請求 → 伺服器 → WSGI → application(environ, start_response)
↓
回傳可迭代 Body
↓
伺服器 → HTTP 回應 → 瀏覽器
WSGI 將「網路 I/O 解析」與「業務邏輯處理」解耦,開發者專注於 application 實作。
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return '<h1>Hello, web!</h1>'
| 參數 | 型別 | 說明 |
|---|---|---|
environ | dict | 包含所有 HTTP 請求資訊:REQUEST_METHOD、PATH_INFO、QUERY_STRING、HTTP_* 頭部等 |
start_response | callable | 發送 HTTP 回應頭的函式,簽名 (status, headers, exc_info=None),只能調用一次 |
# hello.py
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return '<h1>Hello, web!</h1>'
# server.py
from wsgiref.simple_server import make_server
from hello import application
httpd = make_server('', 8000, application)
print("Serving HTTP on port 8000...")
httpd.serve_forever()



def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
name = environ['PATH_INFO'][1:] or 'web'
return '<h1>Hello, %s!</h1>' % name

訪問 https://localhost:8000/Michael 顯示 Hello, Michael!
可呼叫物件不限於函式,類別實例實作 __call__ 亦可:
class App:
def __init__(self, config):
self.config = config
def __call__(self, environ, start_response):
# 處理邏輯
pass
application = App(config)
純 WSGI 處理路由需手動解析 PATH_INFO,不易維護:
def application(environ, start_response):
method = environ['REQUEST_METHOD']
path = environ['PATH_INFO']
if method == 'GET' and path == '/':
return handle_home(environ, start_response)
if method == 'POST' and path == '/signin':
return handle_signin(environ, start_response)
# ... 無限 if-else
Web 框架(Flask、Django、Tornado 等)在 WSGI 之上抽象出:
environ 提供友善 APIstart_response + Body| 伺服器 | 特性 | 適用場景 |
|---|---|---|
| Gunicorn | Pre-fork Worker、支援 gevent | 通用生產環境首選 |
| uWSGI | 功能豐富、Emperor 模式、C 擴充 | 大規模部署、多租戶 |
| Waitress | 純 Python、Windows 相容 | 跨平台部署 |
| wsgiref | 標準庫參考實作、單執行緒 | 僅限開發測試 |