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.
Python code
22 linesimport 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
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
- Use `http.server.HTTPServer` instead of `socketserver.TCPServer` for more control over request handling
- 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
More from Automation & scripting
- Batch Rename Hundreds of Files in Python easy
- Build a Command-Line Password Generator in Python easy
- Build a Complete Web Scraper with Requests and BeautifulSoup in Python medium
- Build a Network Ping Monitor in Python medium
- Create a Local Search Engine to Instantly Find Files on Your Computer in Python medium
- Detect and Remove Blurry Images in Python with OpenCV medium
Keep learning
Related tutorials and quizzes for this topic.