create a http server in python

To create an HTTP server in Python, you can use the built-in http.server module. Here is an example code to create a basic HTTP server:

main.py
import http.server
import socketserver

PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()
220 chars
10 lines

In this code, we import the necessary modules, define the port to listen on (in this example, 8080), and use the socketserver module to create a TCP server that listens on that port. We also define a SimpleHTTPRequestHandler which handles incoming HTTP requests.

Finally, we call the serve_forever() method on the server object to start listening for incoming requests. You can access the server by visiting http://localhost:8080 in your web browser.

gistlibby LogSnag