萬盛學電腦網

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

WSGI 接口深度解析:Python Web 應用與伺服器的標準協議規範

WSGI (Web Server Gateway Interface) 是 Python Web 應用與伺服器溝通的標準介面 (PEP 3333)。本文從 HTTP 協議本質切入,詳細解析 WSGI 介面定義、application 可呼叫物件、environ 與 start_response 參數、內建 wsgiref 伺服器測試,並引導進入 Web 框架抽象層。

Web 應用本質與 WSGI 定位

瀏覽器 → HTTP 請求 → 伺服器 → WSGI → application(environ, start_response)
                                    ↓
                              回傳可迭代 Body
                                    ↓
                              伺服器 → HTTP 回應 → 瀏覽器

WSGI 將「網路 I/O 解析」與「業務邏輯處理」解耦,開發者專注於 application 實作。

最小 WSGI 應用:Hello World

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return '<h1>Hello, web!</h1>'

兩個核心參數詳解

參數型別說明
environdict包含所有 HTTP 請求資訊:REQUEST_METHOD、PATH_INFO、QUERY_STRING、HTTP_* 頭部等
start_responsecallable發送 HTTP 回應頭的函式,簽名 (status, headers, exc_info=None),只能調用一次

使用 wsgiref 內建伺服器測試

# 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()

動態路由範例:讀取 PATH_INFO

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!

WSGI 應用進階結構

可呼叫物件不限於函式,類別實例實作 __call__ 亦可:

class App:
    def __init__(self, config):
        self.config = config
    def __call__(self, environ, start_response):
        # 處理邏輯
        pass

application = App(config)

從 WSGI 到 Web 框架

純 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 之上抽象出:

  • 路由系統:URL 模式 → 處理函式映射
  • 請求物件:封裝 environ 提供友善 API
  • 回應物件:封裝 start_response + Body
  • 中介軟件:橫切關注點(認證、日誌、CORS)

生產環境 WSGI 伺服器選擇

伺服器特性適用場景
GunicornPre-fork Worker、支援 gevent通用生產環境首選
uWSGI功能豐富、Emperor 模式、C 擴充大規模部署、多租戶
Waitress純 Python、Windows 相容跨平台部署
wsgiref標準庫參考實作、單執行緒僅限開發測試
copyright © 萬盛學電腦網 all rights reserved