From a684c8b9df88f988692ed7842e6374ddacb7375c Mon Sep 17 00:00:00 2001 From: Kumi Date: Wed, 10 Jul 2024 09:37:55 +0200 Subject: [PATCH] feat: add built-in HTTP server to preview static site Introduced a new option `--serve` in `main.py` to provide an HTTP server for previewing the static site. Updated README with usage instructions. This enhancement allows users to quickly view the site on localhost without manually opening the `index.html` file. Addresses usability improvements for local development. --- README.md | 3 ++- main.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b65eb20..1219033 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,8 @@ python main.py ``` The website will be built into the `build` directory, and you can view it by -opening the `index.html` file in your browser. +opening the `index.html` file in your browser or using the included HTTP server +(`python main.py --serve`). ## License diff --git a/main.py b/main.py index aed5419..bf76168 100644 --- a/main.py +++ b/main.py @@ -4,6 +4,10 @@ import pathlib import datetime import shutil +from http.server import SimpleHTTPRequestHandler +from socketserver import TCPServer +from threading import Thread + from argparse import ArgumentParser from helpers.finances import ( @@ -12,6 +16,10 @@ from helpers.finances import ( get_latest_month, ) +class StaticPageHandler(SimpleHTTPRequestHandler): + def __init__(self, *args, **kwargs): + super().__init__(*args, directory="build", **kwargs) + # Configure Jinja2 environment env = Environment(loader=FileSystemLoader("templates")) @@ -142,6 +150,16 @@ def generate_static_site(development_mode=False): if __name__ == "__main__": parser = ArgumentParser(description="Generate the private.coffee static site.") parser.add_argument("--dev", action="store_true", help="Enable development mode") + parser.add_argument("--serve", action="store_true", help="Serve the site after building") + parser.add_argument("--port", type=int, default=8000, help="Port to serve the site on") + args = parser.parse_args() generate_static_site(development_mode=args.dev) + + if args.serve: + server = TCPServer(("", args.port), StaticPageHandler) + print(f"Serving on http://localhost:{args.port}") + thread = Thread(target=server.serve_forever) + thread.start() + thread.join() \ No newline at end of file