To create a HTTP server in Python, we can use the http.server
module that comes built-in with Python. To read the request body as binary, we need to use the BytesIO
class from the io
module.
Here's an example code snippet that creates a HTTP server and reads the request body as binary:
main.py671 chars22 lines
In this example, we create a subclass of BaseHTTPRequestHandler
which reads the request body as binary and sends a response. We then create an instance of HTTPServer
with the localhost
and PORT
parameters and call serve_forever()
to run the server indefinitely.
Note: The BytesIO
class is used to work with binary data in-memory, similar to how a StringIO
class is used to work with strings in-memory. We read the request body as bytes using self.rfile.read()
and then use io.BytesIO()
to convert the bytes to an in-memory binary stream object.
gistlibby LogSnag