Serving Files with Python Simple HTTP Server
Today, I began reading Head First HTML/CSS, 2nd Edition. The book starts by guiding you through creating basic HTML files and viewing them in a web browser. By chapter 4, it suggests moving your files onto a web server, but I suspected there might be a more efficient way to do this.
Instead, I put this quick snippet together for hosting files from my WSL2 environment. This allows me to quickly serve the files for any chapter locally.
import socketserver
from functools import partial
from http.server import SimpleHTTPRequestHandler
from pathlib import Path
def main(directory: Path = Path('.'), host: str = '', port: int = 8000):
handler = partial(SimpleHTTPRequestHandler, directory=directory)
with socketserver.TCPServer((host, port), handler) as httpd:
print(f'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:
- Check this gist for a CORS anywhere version
Subscribe to this blog's RSS feed