Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

Create a Simple HTTP File Server in Python

This code creates a simple HTTP file server that serves files from the current working directory on port 8000 using Python's built-in http.server module.

Easy Python 3.7+ Jun 27, 2026 Automation & scripting 30 views 0 copies

Python code

22 lines
Python 3.7+
import http.server
import socketserver
import os

PORT = 8000
DIRECTORY = os.getcwd()

class CustomHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

    def log_message(self, format, *args):
        print(f"[{self.log_date_time_string()}] {args[0]} {args[1]} {args[2]}")

if __name__ == "__main__":
    print(f"Serving HTTP on http://localhost:{PORT} from {DIRECTORY}")
    with socketserver.TCPServer(("", PORT), CustomHandler) as httpd:
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nServer stopped.")
            httpd.server_close()

Output

stdout
Serving HTTP on http://localhost:8000 from /path/to/current/directory
[12/Jan/2025 14:30:00] "GET / HTTP/1.1" 200 -
[12/Jan/2025 14:30:15] "GET /index.html HTTP/1.1" 200 -

How it works

The SimpleHTTPRequestHandler serves files from a specified directory. By default it uses the current working directory, but you can override the directory parameter in the constructor. The custom log_message method prints a clean log line with timestamp, HTTP method, path, and status code. The server runs until interrupted by Ctrl+C, then closes gracefully. This uses zero external dependencies — only the Python standard library.

Common mistakes

  • Using `socketserver.ForkingMixIn` or `ThreadingMixIn` without proper handling for concurrent requests
  • Not closing the server socket when exiting, which can leave ports occupied
  • Serving from a directory with large files without setting a timeout or buffer size

Variations

  1. Use `http.server.HTTPServer` instead of `socketserver.TCPServer` for more control over request handling
  2. Add `ThreadingTCPServer` or `ForkingMixIn` to handle multiple concurrent connections

Real-world use cases

  • Quickly sharing files across a local network during development or team work.
  • Hosting static build outputs (like HTML, CSS, JS) for preview before deployment.
  • Running a lightweight read-only file server for temporary data distribution in testing environments.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.