To create an HTTP server in Python, you can use the built-in http.server
module. Here's an example:
main.py407 chars13 lines
In this example, we define a custom handler class MyHandler
which inherits from BaseHTTPRequestHandler
. We override the do_GET
method to handle incoming GET requests. Inside this method, we call the send_response
method to send an HTTP 200 OK status code, followed by the send_header
method to set the Content-type
and X-Custom-Header
headers. Finally, we call the end_headers
method to finish the header section, and write the response body using the wfile
attribute.
We then create an instance of HTTPServer
and pass it our handler class and the desired server address and port. Finally, we call the serve_forever
method to start accepting incoming requests.
gistlibby LogSnag