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.py665 chars22 linesIn 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.
gistlibby LogSnag