return a binary response from a http server in python

To return a binary response from a HTTP server in Python, you can set the Content-Type header to application/octet-stream which indicates that the response is in binary format, and then return the binary data as the content of the response.

Here's an example using the built-in http.server module:

main.py
import http.server
import socketserver

PORT = 8000

class BinaryHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'application/octet-stream')
        self.end_headers()
        binary_data = b'\x00\x01\x02\x03'  # replace with your binary data
        self.wfile.write(binary_data)

with socketserver.TCPServer(('', PORT), BinaryHandler) as httpd:
    print(f'Serving on port {PORT}')
    httpd.serve_forever()
502 chars
17 lines

This starts an HTTP server on port 8000 that returns dummy binary data (b'\x00\x01\x02\x03') for every GET request.

gistlibby LogSnag