aboutsummaryrefslogtreecommitdiff
path: root/main.py
diff options
context:
space:
mode:
authorErg <uinarf@autistici.org>2024-11-28 16:40:51 +0100
committerErg <uinarf@autistici.org>2024-11-28 16:40:51 +0100
commitbf8efbce7f202f1f7650f628955fb0e42d343a1f (patch)
treed80a2556b24efdd4a9e0d8e6f5f6a11bcb3b5afd /main.py
downloadfastapi_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.py58
1 files changed, 58 insertions, 0 deletions
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",
+ )