How to Create a Python HTTP Server?

Estimated read time 2 min read

In Python, you can create an HTTP server using the built-in http.server module. Here’s an example of how to create a basic HTTP server that listens on port 8000 and serves files from the current directory:

import http.server
import socketserver

PORT = 8000

# Create a handler to serve files from the current directory
handler = http.server.SimpleHTTPRequestHandler

# Create a socket server to listen on the specified port
with socketserver.TCPServer(("", PORT), handler) as httpd:
    print(f"Serving at port {PORT}")
    # Start the server and keep it running until interrupted

This code creates a SimpleHTTPRequestHandler that serves files from the current directory. It then creates a TCP server that listens on port 8000 and uses the handler to handle incoming requests.

When the server is started, it prints a message indicating the port it is listening on, and then enters a loop to keep the server running until interrupted.

To use this HTTP server, save this code to a file, such as, in the directory you want to serve files from. Then, open a command prompt or terminal window in that directory and run the command python to start the server.

You can access the server in a web browser by navigating to http://localhost:8000 or This will display the directory listing of the current directory, and you can click on any file to view it in the browser.

Note that this is a simple example of an HTTP server, and it may not be suitable for production use or serving large amounts of traffic. For more complex requirements, you may want to use a third-party library or web framework, such as Flask or Django.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply