from fastapi import FastAPI, Request from fastapi.staticfiles import StaticFiles from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates import json import os from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware from fastapi import FastAPI from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request class ProxyHeadersMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): # Fix protocol and host based on headers sent by NGINX proto = request.headers.get("X-Forwarded-Proto", "http") host = request.headers.get("X-Forwarded-Host") if proto: request.scope["scheme"] = proto if host: request.headers["host"] = host response = await call_next(request) return response app = FastAPI() # Mount static files app.mount("/static", StaticFiles(directory="static"), name="static") app.add_middleware(ProxyHeadersMiddleware, allowed_hosts=["*"]) # Templates directory templates = Jinja2Templates(directory="templates") # Load JSON data with open("mock_data.json") as file: data = json.load(file) # Index route @app.get("/", response_class=HTMLResponse) async def get_index(request: Request): return templates.TemplateResponse( "index.html", {"request": request, "data": data, "page_title": "Forside", "author": "Henrik"} ) # Category route @app.get("/category/{category_name}", response_class=HTMLResponse) async def get_category(request: Request, category_name: str): # Find den korrekte kategori category = next((cat for cat in data["categories"] if cat["path"] == category_name), None) if category: category_file = f"data/{category_name}/index.html" if os.path.exists(category_file): with open(category_file) as file: category_content = file.read() return templates.TemplateResponse( "category.html", { "request": request, "data": data, "page_title": category["name"], "author": category["author"], "content": category_content }, ) return HTMLResponse("Kategori ikke fundet", status_code=404)