diff options
author | Erg <uinarf@autistici.org> | 2024-11-28 16:40:51 +0100 |
---|---|---|
committer | Erg <uinarf@autistici.org> | 2024-11-28 16:40:51 +0100 |
commit | bf8efbce7f202f1f7650f628955fb0e42d343a1f (patch) | |
tree | d80a2556b24efdd4a9e0d8e6f5f6a11bcb3b5afd /main.py | |
download | fastapi_blog-master.tar.gz fastapi_blog-master.tar.bz2 fastapi_blog-master.zip |
Initial commit. Serving main page and static html files, extra 404 error, contains openrc service file and accompanying scriptHEADmaster
Diffstat (limited to 'main.py')
-rw-r--r-- | main.py | 58 |
1 files changed, 58 insertions, 0 deletions
@@ -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", + ) |