Files
LucasJensen/server/main.py
Lucas Jensen a8b6807b79 reorganized
2024-07-06 10:36:37 -07:00

82 lines
2.2 KiB
Python

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from model import queries
from types import About, Project, Lucas
load_dotenv()
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:3000",
"https://localhost:3000",
"http://127.0.0.1:3000",
"https://lucasjensen.me/",
"https://lucasjensen.me",
"https://www.lucasjensen.me/",
"https://www.lucasjensen.me",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/", status_code=status.HTTP_200_OK)
async def root() -> Lucas:
lucas = Lucas(about=queries.get_about(), projects=queries.get_projects())
return lucas
@app.get("/about", status_code=status.HTTP_200_OK)
async def about() -> About:
try:
return queries.get_about()
except Exception as e:
print(f"err getting about: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"database error: {e}",
)
@app.get("/projects", status_code=status.HTTP_200_OK)
async def projects() -> list[Project]:
try:
return queries.get_projects()
except Exception as e:
print(f"err getting projects: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"database error: {e}",
)
@app.get("/projects/{project_id}", status_code=status.HTTP_200_OK)
async def project(project_id: int) -> Project:
project = None
try:
project = queries.get_project(project_id)
except Exception as e:
print(f"err getting projects: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"database error: {e}",
)
if project is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"project with id {project_id} not found",
)
return project