emptygif
Ngôn ngữ: Tiếng Việt

Tất cả ngôn ngữ và framework

Python standard library (http.server) Python

Đoạn mã Python cho Python standard library (http.server), trả lời các yêu cầu tới /pixel.gif bằng GIF rỗng, được giải mã một lần khi khởi động.

Python standard library (http.server) Python

Tệp
server.py
Chạy
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()

Chúng tôi đã chạy đoạn mã này và so sánh các byte nó trả về.

Kiểm tra

curl -sI http://localhost:8080/pixel.gif

Trang chính thức: Python standard library (http.server)

Thêm với Python