From bf8efbce7f202f1f7650f628955fb0e42d343a1f Mon Sep 17 00:00:00 2001 From: Erg Date: Thu, 28 Nov 2024 16:40:51 +0100 Subject: Initial commit. Serving main page and static html files, extra 404 error, contains openrc service file and accompanying script --- main.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 main.py (limited to 'main.py') diff --git a/main.py b/main.py new file mode 100644 index 0000000..8d76231 --- /dev/null +++ b/main.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python + +""" +FastAPI site serving static html files. +""" + +from os import listdir +import uvicorn +from fastapi import FastAPI, Request +from fastapi.staticfiles import StaticFiles +from fastapi.templating import Jinja2Templates +from fastapi.exceptions import HTTPException + +ARTICLES = 'static/html' + +templates = Jinja2Templates(directory="templates") + +LIST_OF_ARTICLES = [i for i in listdir(ARTICLES) if i.endswith('.html')] + + +async def page_not_found(request: Request, exc: HTTPException): + """Return 404 page""" + return templates.TemplateResponse( + 'error_404/error_404.html', { + 'request': request, + }, + status_code=404 + ) + +exception_handlers = { + 404: page_not_found, + } + +app = FastAPI(exception_handlers=exception_handlers) + +app.mount("/static", StaticFiles(directory="static"), name="static") + + +@app.get("/") +async def main_page(request: Request): + """Generate main page""" + return templates.TemplateResponse( + "main_page.html", { + "request": request, + "files": LIST_OF_ARTICLES, + "static": ARTICLES, + } + ) + + +if __name__ == "__main__": + uvicorn.run( + app, + port=8000, + host='127.0.0.1', + log_level="debug", + uds="/run/tech_blog.sock", + ) -- cgit v1.2.3-65-gdbad