heroweb/poc/server.py

78 lines
2.3 KiB
Python
Raw Normal View History

2024-08-22 10:09:10 +00:00
from fastapi import FastAPI, Request, HTTPException
2024-09-01 18:00:13 +00:00
from fastapi.responses import HTMLResponse, FileResponse
2024-08-22 10:09:10 +00:00
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from jinja2 import Environment, FileSystemLoader, select_autoescape
2024-09-01 18:00:13 +00:00
from webcomponents.tasks.web import render as render_tasks
from tools.deduper import Deduper
2024-08-22 10:09:10 +00:00
import os
2024-09-01 18:00:13 +00:00
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"
2024-08-22 10:09:10 +00:00
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)
2024-09-01 18:00:13 +00:00
@app.get('/favicon.ico', include_in_schema=False)
async def favicon():
return FileResponse(f"{static_dir}/favicon.ico")
2024-08-22 10:09:10 +00:00
@app.get("/", response_class=HTMLResponse)
async def read_index(request: Request):
template = env.get_template("index.html")
return template.render(request=request)
2024-09-01 18:00:13 +00:00
@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)
2024-08-22 10:09:10 +00:00
@app.get("/{template_name}", response_class=HTMLResponse)
async def read_template(request: Request, template_name: str):
#import pudb; pudb.set_trace()
2024-09-01 18:00:13 +00:00
try:
template = env.get_template(template_name)
return template.render(request=request)
except:
return ""
2024-08-22 10:09:10 +00:00
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)