emptygif
言語: 日本語

すべての言語・フレームワーク

Python standard library (http.server) Python

/pixel.gif へのリクエストに空の GIF を返す、Python standard library (http.server) 用の Python スニペット。GIF は起動時に一度だけデコードします。

Python standard library (http.server) Python

ファイル
server.py
実行
python3 server.py
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)

Python の他の例