return a html response from a http server in python

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer

PORT = 8080

class Handler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

        # HTML content to be sent
        html_response = "<html><body><h1>Hello, World!</h1></body></html>"

        # Sending the html content to client
        self.wfile.write(bytes(html_response, "utf-8"))

httpd = HTTPServer(('localhost', PORT), Handler)
print(f"Server running on port {PORT}")

# Start the server
httpd.serve_forever()
592 chars
23 lines

In the above code, we define a Handler class which inherits from BaseHTTPRequestHandler and where we implement the do_GET method to handle the incoming HTTP GET request.

Inside this method, we first set the response status code to 200 and set the response header Content-type to text/html.

After that, we define the HTML content to be sent in the html_response variable and send it to the client using the wfile object.

Finally, we create an instance of HTTPServer on the localhost and the specified port, and then start it using the serve_forever() method.

gistlibby LogSnag