Sometimes when working on JavaScript-based applications or static websites, it's necessary to be able to serve the content of a directory directly from disk.
The Python standard library has a ready-made HTTP server that handles requests, mapping them to files in a directory, so we can quickly roll our own HTTP server to write websites without the need to install any other tool.
The http.server
module provides most of what is needed to implement an HTTP server in charge of serving content of a directory:
import os.path import socketserver from http.server import SimpleHTTPRequestHandler, HTTPServer def serve_directory(path, port=8000): class ConfiguredHandler(HTTPDirectoryRequestHandler): SERVED_DIRECTORY = path httpd = ThreadingHTTPServer(("", port), ConfiguredHandler) print("serving on port", port) try: httpd.serve_forever() except KeyboardInterrupt: httpd.server_close() class ThreadingHTTPServer(socketserver...