create a http server with a head route in python

Here is the code to create a HTTP server with a HEAD route in Python:

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer

class RequestHandler(BaseHTTPRequestHandler):
    def do_HEAD(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

def run(server_class=HTTPServer, handler_class=RequestHandler, port=8080):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Starting httpd on port {port}...')
    httpd.serve_forever()

if __name__ == '__main__':
    run()
517 chars
17 lines

The RequestHandler class overrides the do_HEAD method to handle the HEAD request. In this example, it simply sends a 200 response with the content type header set to text/html.

The run function creates an instance of HTTPServer using server_class and handler_class, and starts the server on the specified port. When the server is started, it will print a message to the console indicating the port number.

Note that, in this example, the server will run indefinitely until it is manually stopped. To stop the server, simply press Ctrl+C in the console.

gistlibby LogSnag