http.server get in python

To create an HTTP server in Python, you can use the built-in http.server module. There are several methods for creating a server, but the most basic one is to use the HTTPServer class and specify the port number you want to use. Here's an example:

main.py
import http.server
import socketserver

PORT = 8000  # specify port number

Handler = http.server.SimpleHTTPRequestHandler

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

In this example, we create a SimpleHTTPRequestHandler to handle incoming requests, and then create a TCPServer object that listens on port 8000. Note that we're using a with block to ensure that the server is properly closed when we're done with it.

Once you run this code, you should be able to navigate to http://localhost:8000 in your web browser and see the default directory listing for the current working directory. You can modify the Handler class to serve other kinds of files or to implement custom behavior, depending on your needs.

related categories

gistlibby LogSnag