Venture_Of_Heros/main.py
2025-02-24 13:35:58 -05:00

48 lines
1.4 KiB
Python

# Imports
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from sql import *
from functions import *
# Create DB on startup
# noinspection PyUnusedLocal
@asynccontextmanager
async def lifespan(app: FastAPI):
create_db_and_tables()
yield # Code before the yield will run on startup, code after yield won't run until the program is over
# Define the app
app = FastAPI(lifespan=lifespan)
# Routes
@app.post("/heroes/create", response_model=HeroPublic)
def create_hero(hero: HeroCreate, session: SessionDep):
db_hero = Hero.model_validate(hero)
session.add(db_hero)
session.commit()
session.refresh(db_hero)
return db_hero
@app.get("/heroes/{type}", response_model=HeroPublic)
def get_hero(type: str, session: SessionDep):
hero = get_hero_by_id(type, session)
if hero is None:
hero = get_hero_by_email(type, session)
if not hero:
raise HTTPException(status_code=404, detail="User not found")
return hero
@app.patch("/heroes/update/{hero_id}/", response_model=HeroPublic)
def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep):
hero_db = session.get(Hero, hero_id)
if not hero_db:
raise HTTPException(status_code=404, detail="Hero not found")
hero_data = hero.model_dump(exclude_unset=True)
hero_db.sqlmodel_update(hero_data)
session.add(hero_db)
session.commit()
session.refresh(hero_db)
return hero_db