Python standard library (http.server) Python
適用於 Python standard library (http.server) 的 Python 程式碼片段,以空 GIF 回應對 /pixel.gif 的請求,GIF 在啟動時只解碼一次。
Python standard library (http.server) Python
import base64
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit
GIF = base64.b64decode("R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==")
class PixelHandler(BaseHTTPRequestHandler):
def do_GET(self):
if urlsplit(self.path).path != "/pixel.gif":
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", "image/gif")
self.send_header("Content-Length", str(len(GIF)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(GIF)
ThreadingHTTPServer(("", 8080), PixelHandler).serve_forever()
我們執行了這段程式碼,並比對了它回傳的位元組。
驗證
curl -sI http://localhost:8080/pixel.gif
官方網站: Python standard library (http.server)