萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python WSGI 介面深度解析:Application、Server、Middleware 三方契約

WSGI (Web Server Gateway Interface, PEP 3333) 定義了 Python Web 框架與伺服器之間的標準介面,是 Django、Flask、FastAPI 等框架能在 Gunicorn、uWSGI、Daphne 上運行的基石。本文深度解析 WSGI 協議規範、Application 可呼叫物件、Server 責任、Middleware 鏈結機制與路由中間件實作範例。

WSGI 協議核心契約

Application (應用程式)

一個**可呼叫物件** (函數、類別實例實現 `__call__`、方法),接受兩個參數:

  1. environ:CGI 風格環境變數字典 (請求資訊)
  2. start_response:回呼函數,用於發送 HTTP 狀態碼與標頭

必須返回**可疊代的字串序列** (通常是列表 `[body_bytes]`) 作為回應主體。

Server (伺服器)

  • 建立 `environ` 字典 (含 `REQUEST_METHOD`, `PATH_INFO`, `QUERY_STRING`, `SERVER_NAME`, `wsgi.input` 等)
  • 提供 `start_response(status, headers)` 回呼
  • 呼叫 Application,獲取回應主體可疊代物
  • 發送狀態行、標頭、主體給客戶端

Middleware (中介軟體)

同時扮演 Server 與 Application 角色:

  • 對 Server:它是 Application (可呼叫,接受 environ/start_response)
  • 對 Application:它是 Server (提供 environ、包裝 start_response、呼叫下游)
  • 本質是**裝飾器模式**,攔截請求/回應,實現日誌、認證、壓縮、路由等橫切關注點。

最小 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]

最小 Server 範例 (wsgiref)


from wsgiref.simple_server import make_server

with make_server('localhost', 8080, application) as httpd:
    print("Serving on https://localhost:8080")
    httpd.serve_forever()

Middleware 實作模式


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)

路由 Middleware 完整範例


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)

environ 關鍵鍵值 (PEP 3333 規範)

start_response 簽名


def start_response(status, response_headers, exc_info=None):
    # status: "200 OK", "404 Not Found"
    # response_headers: [(header_name, header_value), ...]
    # exc_info: sys.exc_info() 用於錯誤處理鏈
    # 返回: write(body_chunk) 函數 (舊式 API,現較少用)

常見中介軟體模式

  • 認證:解析 JWT/Session,將 `user` 存入 `environ['wsgi.user']`
  • CORS:在 `start_response` 包裝中添加 `Access-Control-Allow-*` 標頭
  • 壓縮:檢查 `Accept-Encoding`,包裝回應主體為 gzip
  • 靜態檔案:匹配路徑直接服務檔案,否則傳遞下游
  • 異常捕獲:`try/except` 包裝下游呼叫,返回 500 頁面

WSGI vs ASGI

WSGI 為同步介面,無法原生支援 WebSocket、Server-Sent Events、長輪詢等雙向通訊。ASGI (Asynchronous Server Gateway Interface) 為非同步後繼標準,支援 `await`、事件驅動、生命週期協程。現代框架 (FastAPI, Starlette, Django 3.1+) 雙支援 WSGI/ASGI。

最佳實踐

  • Application 物件**必須可重入** (多執行緒/多進程並發呼叫)。
  • 回應主體**必須為 bytes** (Python 3),不可為 str。
  • 大檔案回應使用生成器逐塊產生,避免記憶體爆炸:`yield chunk`。
  • 中介軟體順序:**外層先執行請求邏輯,內層後執行回應邏輯** (洋蔥模型)。
  • 生產環境**勿使用 wsgiref**,改用 Gunicorn + Gevent/Meinheld 或 uWSGI。
copyright © 萬盛學電腦網 all rights reserved
鍵說明範例
REQUEST_METHODHTTP 方法GET, POST
SCRIPT_NAME應用掛載路徑前綴/myapp
PATH_INFO請求路徑 (相對 SCRIPT_NAME)/users/123
QUERY_STRING查詢字串 (未解析)page=1&size=20
CONTENT_TYPE請求 Content-Typeapplication/json
CONTENT_LENGTH請求主體長度123
SERVER_NAME伺服器主機名localhost
SERVER_PORT伺服器埠號8000
wsgi.input請求主體輸入流 (file-like)io.BytesIO
wsgi.errors錯誤輸出流sys.stderr
wsgi.versionWSGI 版本元組(1, 0)
wsgi.multithread是否多執行緒True/False
wsgi.multiprocess是否多進程True/False
wsgi.run_once是否單次請求 (CGI)False