Refactor: Make use of pydantic schemas where possible

This commit is contained in:
Colin Goutte 2023-08-26 23:33:53 +02:00
parent 4543f2f0d7
commit 5c00c51b43
3 changed files with 13 additions and 18 deletions

View File

@ -25,7 +25,7 @@ def fill_db():
import random
def _genres():
random.choice([["Comedy"], ["Comedy", "Drama"], []])
return random.choice(["Comedy"], ["Comedy", "Drama"], [])
for _ in range(3):
name = f"fill_db_{random.randint(1, 1000):03}"

23
dev.py
View File

@ -54,7 +54,7 @@ async def create_movie(payload: schemas.MoviePayload, db: Session = Depends(get_
@app.put("/movies/{id_}")
async def update_movie(
id_: str, db: Session = Depends(get_db), request: Request = None
):
) -> schemas.MovieObject:
try:
movie = crud.get_movie_by_id(db, id_)
except LookupError:
@ -74,24 +74,21 @@ async def update_movie(
movie = crud.update_movie(db, id_, **crud_params)
out = {k: v for (k, v) in movie.__dict__.items() if not k.startswith("_")}
return out
return movie
@app.get("/movies/{id_}")
async def get_movie(id_: str, db: Session = Depends(get_db)):
async def get_movie(id_: str, db: Session = Depends(get_db)) -> schemas.MovieObject:
try:
movie = crud.get_movie_by_id(db, id_)
out = {k: v for (k, v) in movie.__dict__.items() if not k.startswith("_")}
except LookupError:
raise HTTPException(status_code=404, detail=f"No movie found with id {id_}")
else:
return out
return movie
@app.delete("/movies/{id_}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_movie(id_: str, db: Session = Depends(get_db)):
async def delete_movie(id_: str, db: Session = Depends(get_db)) -> None:
try:
movie = crud.delete_movie_by_id(db, id_)
except LookupError:
@ -99,14 +96,8 @@ async def delete_movie(id_: str, db: Session = Depends(get_db)):
@app.get("/movies/")
async def list_movie(db: Session = Depends(get_db)):
movies = crud.get_all_movies(db)
out = [
{k: v for (k, v) in movie.__dict__.items() if not k.startswith("_")}
for movie in movies
]
return out
async def list_movie(db: Session = Depends(get_db)) -> list[schemas.MovieObject]:
return crud.get_all_movies(db)
if __name__ == "__main__":

View File

@ -4,9 +4,13 @@ from pydantic import BaseModel
class MoviePayload(BaseModel):
title: str
vote_count: int = 0
vote_count: int | None = 0
vote_average: float | None = None
genres: list[str] = []
description: str = ""
release_date: str | None = None # Use custom formatted string validation
class MovieObject(MoviePayload):
id: int | str