Serving Files with Python Simple HTTP Server

So today I started reading Head First HTML/CSS 2e. The book begins by showing you how to create simple HTML files and loading them into a web browser. At chapter 4 it directs you to move your files onto a webserver.

Instead, I put this quick snippet together for hosting any files from my WSL2 environment. It accepts a single argument, the directory name. This allows me to quickly serve the files for any chapter locally.

import http.server
import socketserver
import argparse

parser = argparse.ArgumentParser(
    prog="Simple HTTP Server",
    description="Serves static files using Python3 Simple HTTP module",
)
parser.add_argument("-d", "--directory", required=True)
args = parser.parse_args()

PORT = 8000
DIRECTORY = args.directory


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


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

Python simple HTTP server only serves static files and is not capable of running server-side scripts. In some of the later chapters you are required to run php files. For these chapters I switched to PHP built-in development server

Further notes:

Subscribe to this blog's RSS feed