Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

用 Twisted 打造專屬 Python Web 伺服器:從靜態檔案到動態渲染

編輯:系統常見問題解答

Twisted 是成熟的 Python 非同步網路引擎,適合快速建構輕量、可控制的 Web 服務。以下最小可行範例:

目錄結構

project/
├── htm/
│   └── index.html
└── web.py

web.py 完整程式碼

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Twisted 靜態檔案伺服器 + 自訂 .html 處理器
"""
import sys
from pathlib import Path

from twisted.web.resource import Resource
from twisted.web import server, static
from twisted.internet import reactor

# 專案根目錄
BASE_DIR = Path(__file__).parent
HTM_DIR = BASE_DIR / "htm"
PORT = 8080  # 避免需 root 權限的 80 埠

class CustomHTML(Resource):
    """自訂 .html 處理器:可在這裡注入模板、變數、權限檢查"""
    def __init__(self, filepath: Path):
        super().__init__()
        self.content = filepath.read_text(encoding="utf-8")

    def render(self, request):
        request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
        # 這裡可動態替換 {{variable}}、檢查 Cookie、Session 等
        return self.content.encode("utf-8")

def main():
    # 靜態檔案根資源
    root = static.File(str(HTM_DIR))
    # 註冊 .html 使用自訂處理器
    root.processors = {b".html": CustomHTML}
    root.indexNames = [b"index.html"]

    site = server.Site(root)
    reactor.listenTCP(PORT, site, interface="0.0.0.0")
    print(f"Twisted HTTP server running on https://0.0.0.0:{PORT}")
    print(f"Serving static files from: {HTM_DIR}")
    reactor.run()

if __name__ == "__main__":
    main()

htm/index.html 範例

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>Twisted Demo</title>
</head>
<body>
    <h1>Hello from Twisted!</h1>
    <p>Server time: <span id="time"></span></p>
    <script>document.getElementById('time').textContent = new Date().toLocaleString();</script>
</body>
</html>

執行與驗證

python3 web.py
# 瀏覽器開啟 https://localhost:8080
# 或 curl -I https://localhost:8080

進階擴充方向

  • 動態路由:root.putChild(b"api", APIResource()) 掛載 REST API。
  • WebSocket:from twisted.web.websocket import WebSocketServerFactory 實作即時通訊。
  • SSL/TLS:reactor.listenSSL(PORT, site, ssl.ContextFactory(...))。
  • 反向代理:proxy.ReverseProxyResource 整合後端微服務。
  • 部署:systemd service + User=www-data + AmbientCapabilities=CAP_NET_BIND_SERVICE (綁 80/443) 或 Nginx 反代。

為什麼選 Twisted?

  • 標準庫無依賴、成熟穩定 (2002 年釋出)、非同步 I/O 原生支援。
  • 協議實作豐富:HTTP/1.1、HTTP/2、WebSocket、SSH、IMAP、DNS、SMTP...
  • 適合「想完全掌控行為、不想被框架綁架」的專案。

幾十行程式碼即可擁有專屬 Web 伺服器,彈性極高,適合嵌入式裝置、測試存桩、微服務閘道、教學示範等場景。

Copyright © Windows教程網 All Rights Reserved