1 min read

Python Http.server Module

The http.server module defines classes for implementing HTTP servers (Web servers).

Importing the Module

import http.server

Basic Usage (Command Line)

You can use the module to run a simple web server from the command line. This is useful for sharing files or testing.

python -m http.server 8000

This serves files from the current directory on port 8000.

Creating a Simple Server

You can create a server programmatically using HTTPServer and SimpleHTTPRequestHandler.

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

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

Custom Request Handler

To handle requests dynamically, you can subclass BaseHTTPRequestHandler.

from http.server import BaseHTTPRequestHandler, HTTPServer

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("<html><body><h1>Hello World!</h1></body></html>", "utf-8"))

if __name__ == "__main__":
    webServer = HTTPServer(("localhost", 8080), MyServer)
    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass
    webServer.server_close()

programming/python/python