create a http server and read the request body as binary and return a binary response in python

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer
import io

class BinaryHandler(BaseHTTPRequestHandler):
    
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        
        # Do some binary processing on the body here
        
        output = b'Response Body as Binary'
        
        self.send_response(200)
        self.send_header('Content-Type', 'application/octet-stream')
        self.send_header('Content-Length', str(len(output)))
        self.end_headers()
        
        self.wfile.write(output)

def run():
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, BinaryHandler)
    httpd.serve_forever()

run()
737 chars
27 lines

This code creates an HTTP server in Python listening on port 8000. It expects a POST request with a binary payload, reads the payload into memory, does some binary processing on the payload and returns a binary response. When a POST request is received, do_POST function is called. It reads the request body from rfile and stores it in the body variable. The binary processing happens in the middle which can vary according to the use case. The response is returned in a similar way, by encoding the binary content in output variable and sending it back as response.

gistlibby LogSnag