WSGI (Web Server Gateway Interface, PEP 3333) 定義了 Python Web 框架與伺服器之間的標準介面,是 Django、Flask、FastAPI 等框架能在 Gunicorn、uWSGI、Daphne 上運行的基石。本文深度解析 WSGI 協議規範、Application 可呼叫物件、Server 責任、Middleware 鏈結機制與路由中間件實作範例。
一個**可呼叫物件** (函數、類別實例實現 `__call__`、方法),接受兩個參數:
environ:CGI 風格環境變數字典 (請求資訊)start_response:回呼函數,用於發送 HTTP 狀態碼與標頭必須返回**可疊代的字串序列** (通常是列表 `[body_bytes]`) 作為回應主體。
同時扮演 Server 與 Application 角色:
def application(environ, start_response):
# environ: CGI 環境變數字典
# start_response: callback(status, headers)
response_body = f'The request method was {environ["REQUEST_METHOD"]}'.encode('utf-8')
status = '200 OK'
response_headers = [
('Content-Type', 'text/plain; charset=utf-8'),
('Content-Length', str(len(response_body))),
]
# 必須在返回主體前呼叫
start_response(status, response_headers)
# 返回可疊代的 bytes 序列
return [response_body]
from wsgiref.simple_server import make_server
with make_server('localhost', 8080, application) as httpd:
print("Serving on https://localhost:8080")
httpd.serve_forever()
class LoggingMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
# 請求前處理
print(f"REQUEST: {environ['REQUEST_METHOD']} {environ['PATH_INFO']}")
# 包裝 start_response 以攔截回應
def logging_start_response(status, headers, exc_info=None):
print(f"RESPONSE: {status}")
return start_response(status, headers, exc_info)
# 呼叫下游應用
return self.app(environ, logging_start_response)
# 使用
app = LoggingMiddleware(application)
import re
def index(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b'index page']
def hello(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b'hello page']
def not_found(environ, start_response):
start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])
return [b'Not Found Page']
# 路由表: (regex_pattern, app_callable)
urls = [
(r'^$', index),
(r'hello/?$', hello),
]
def application(environ, start_response):
path = environ.get('PATH_INFO', '').lstrip('/')
for regex, callback in urls:
match = re.search(regex, path)
if match is not None:
# 可將 match 物件存入 environ 供下游使用
environ['url_match'] = match
return callback(environ, start_response)
return not_found(environ, start_response)
| 鍵 | 說明 | 範例 |
|---|---|---|
REQUEST_METHOD | HTTP 方法 | GET, POST |
SCRIPT_NAME | 應用掛載路徑前綴 | /myapp |
PATH_INFO | 請求路徑 (相對 SCRIPT_NAME) | /users/123 |
QUERY_STRING | 查詢字串 (未解析) | page=1&size=20 |
CONTENT_TYPE | 請求 Content-Type | application/json |
CONTENT_LENGTH | 請求主體長度 | 123 |
SERVER_NAME | 伺服器主機名 | localhost |
SERVER_PORT | 伺服器埠號 | 8000 |
wsgi.input | 請求主體輸入流 (file-like) | io.BytesIO |
wsgi.errors | 錯誤輸出流 | sys.stderr |
wsgi.version | WSGI 版本元組 | (1, 0) |
wsgi.multithread | 是否多執行緒 | True/False |
wsgi.multiprocess | 是否多進程 | True/False |
wsgi.run_once | 是否單次請求 (CGI) | False |