Twisted 是成熟的 Python 非同步網路引擎,適合快速建構輕量、可控制的 Web 服務。以下最小可行範例:
project/
├── htm/
│ └── index.html
└── 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()
<!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。from twisted.web.websocket import WebSocketServerFactory 實作即時通訊。reactor.listenSSL(PORT, site, ssl.ContextFactory(...))。proxy.ReverseProxyResource 整合後端微服務。User=www-data + AmbientCapabilities=CAP_NET_BIND_SERVICE (綁 80/443) 或 Nginx 反代。幾十行程式碼即可擁有專屬 Web 伺服器,彈性極高,適合嵌入式裝置、測試存桩、微服務閘道、教學示範等場景。