create a http server on a specific port and host in python

To create an HTTP server in Python, you can make use of the http module that comes along with Python 3 onwards. The http.server module provides classes for implementing HTTP servers that can listen to requests.

Here is how you can create an HTTP server on a specific port and host in Python. In this example, we will create a server on localhost (i.e., 127.0.0.1) with port number 8080.

main.py
import http.server
import socketserver

# Set the host name and port number
host_name = "localhost"
port_number = 8080

# Define the HTTP request handler
class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(b"Hello, world!")  # Response body

# Create an HTTP server object and bind it to the specified port and host
httpd = socketserver.TCPServer((host_name, port_number), MyHttpRequestHandler)

# Start the server
print(f"Server started on {host_name}:{port_number}")
httpd.serve_forever()
665 chars
22 lines

In the above code, we first import the required modules http.server and socketserver. We then define a request handler class MyHttpRequestHandler that handles the incoming HTTP requests. In this case, we have defined a simple response that sends the message "Hello, world!" in the response body.

We then create an HTTP server object httpd and bind it to the specified host and port using the socketserver.TCPServer() method. Finally, we start the server using the serve_forever() method.

You can run this script in the terminal using the command python <filename>.py and access the server in your web browser by navigating to localhost:8080.

related categories

gistlibby LogSnag