自己動手寫 Web 伺服器的最大好處,就是能完全掌控實作細節,並依自己的習慣設計互動方式。而 Python 的 Twisted 框架底層以 C 撰寫 TCP,HTTP、SMTP 等高層協定則用 Python 實作,擴充起來格外順手。本文用一段程式碼帶你快速上手。
先在 htm 目錄下放一個以 .html 結尾的檔案,接著在 htm 的上一層目錄建立 web.py,內容如下:
PORT = 80 # 若 80 埠被占用,換成其他埠號
from twisted.web.resource import Resource
from twisted.web import server
from twisted.web import static
from twisted.internet import reactor
class ReStructured(Resource):
def __init__(self, filename, *a):
self.rst = open(filename).read()
def render(self, request):
return self.rst
resource = static.File('./htm/')
resource.processors = { '.html': ReStructured }
resource.indexNames = [ 'index.html' ]
reactor.listenTCP(PORT, server.Site(resource))
reactor.run()
在控制台進入該目錄,執行 python web.py,然後打開瀏覽器輸入 https://127.0.0.1。如果看見你的站點,恭喜你——一個由 Twisted 驅動、可自由擴充的極簡 Web 伺服器就這樣誕生了。透過它,你能清楚理解 HTTP 請求如何被接收、處理與回應,也為後續自訂功能打好了基礎。