heroweb/poc/server.py
2024-09-02 07:28:06 +02:00

84 lines
2.7 KiB
Python

from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from jinja2 import Environment, FileSystemLoader, select_autoescape
#from webcomponents.tasks.web import render as render_tasks
from tools.deduper import Deduper
import os
from jinja2 import TemplateNotFound
mypath="~/code/git.ourworld.tf/despiegk/heroweb/poc"
p = os.path.abspath(os.path.expanduser(mypath))
if not os.path.exists(p):
raise FileNotFoundError(f"The path does not exist: {p}")
deduper = Deduper(f"{p}/static")
#from IPython import embed;embed()
sources_dir = f"{p}/out"
static_dir = f"{p}/static"
app = FastAPI()
if not os.path.exists(static_dir):
raise RuntimeError(f"The directory '{static_dir}' does not exist.")
if not os.path.exists(sources_dir):
raise RuntimeError(f"The templates dir '{sources_dir}' does not exist.")
# Mount the static files directory
app.mount("/static", StaticFiles(directory=static_dir), name="static")
app.mount("/assets", StaticFiles(directory=static_dir), name="assets")
env = Environment(
loader=FileSystemLoader(sources_dir),
autoescape=select_autoescape(['html', 'xml'])
)
# Initialize Jinja2 templates
templates = Jinja2Templates(directory=sources_dir)
@app.get('/favicon.ico', include_in_schema=False)
async def favicon():
return FileResponse(f"{static_dir}/favicon.ico")
@app.get("/", response_class=HTMLResponse)
async def read_index(request: Request):
template = env.get_template("index.html")
return template.render(request=request)
# @app.get("/tasks", response_class=HTMLResponse)
# async def get_tasks(request: Request):
# #import pudb; pudb.set_trace()
# template = env.get_template("tasks.html")
# r = template.render(request=request)
# body = render_tasks(deduper=deduper)
# r = r.replace("BODY",body)
# print(r)
# return HTMLResponse(content=r)
@app.get("/{template_path:path}", response_class=HTMLResponse)
async def read_template(request: Request, template_path: str):
try:
# Ensure the template path ends with .html
if not template_path.endswith('.html'):
template_path += '.html'
# Try to get the template
template = env.get_template(template_path)
return template.render(request=request)
except TemplateNotFound:
raise HTTPException(status_code=404, detail=f"Template not found: {template_path}")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
#no need to do this every time
import uvicorn
uvicorn.run("server:app", host="127.0.0.1", port=8000, reload=True)