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 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") 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_name}", response_class=HTMLResponse) async def read_template(request: Request, template_name: str): #import pudb; pudb.set_trace() try: template = env.get_template(template_name) return template.render(request=request) except: return "" 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)