__init__.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from typing import List
  2. from sqlmodel import Session, select
  3. from fastapi import FastAPI, HTTPException, status
  4. from .models import engine, Hero, create_tables
  5. from .serializers import HeroRead, HeroCreate, HeroUpdate
  6. app = FastAPI()
  7. @app.on_event("startup")
  8. def on_startup():
  9. create_tables(engine)
  10. @app.post("/heroes", response_model=HeroRead)
  11. def create_hero(data: HeroCreate):
  12. hero = Hero(**data.dict())
  13. with Session(engine) as session:
  14. session.add(hero)
  15. session.commit()
  16. session.refresh(hero)
  17. return hero
  18. @app.get("/heroes", response_model=List[HeroRead])
  19. def read_heroes():
  20. with Session(engine) as session:
  21. heroes = session.exec(select(Hero)).all()
  22. return heroes
  23. @app.get('/heroes/pk', response_model=HeroRead)
  24. def retrieve_hero(pk: int):
  25. with Session(engine) as session:
  26. instance = session.get(Hero, pk)
  27. if not instance:
  28. raise HTTPException(
  29. detail='Hero not found',
  30. status_code=status.HTTP_404_NOT_FOUND
  31. )
  32. return instance
  33. @app.patch('/heroes/{pk}', response_model=HeroRead)
  34. def update_hero(pk: int, data: HeroUpdate):
  35. with Session(engine) as session:
  36. instance = session.get(Hero, pk)
  37. if not instance:
  38. raise HTTPException(
  39. detail='Hero not found',
  40. status_code=status.HTTP_404_NOT_FOUND
  41. )
  42. hero_data = data.dict(exclude_unset=True)
  43. for key, value in hero_data.items():
  44. setattr(instance, key, value)
  45. session.add(instance)
  46. session.commit()
  47. session.refresh(instance)
  48. return instance