heroweb/poc/server.py

49 lines
1.4 KiB
Python
Raw Normal View History

2024-08-22 10:09:10 +00:00
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from jinja2 import Environment, FileSystemLoader, select_autoescape
import os
sources_dir = "ex1/out"
static_dir = f"{sources_dir}/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("/", response_class=HTMLResponse)
async def read_index(request: Request):
template = env.get_template("index.html")
return template.render(request=request)
@app.get("/{template_name}", response_class=HTMLResponse)
async def read_template(request: Request, template_name: str):
#import pudb; pudb.set_trace()
template = env.get_template(template_name)
return template.render(request=request)
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)