Skip to content

Commit

Permalink
Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
kapitoshk4 committed Jan 15, 2025
1 parent 9aa1b96 commit c32c69f
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 3 deletions.
41 changes: 39 additions & 2 deletions src/routes/movies.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,47 @@
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional

from database import get_db, MovieModel

from schemas.movies import MovieDetailResponseSchema, MovieListResponseSchema

router = APIRouter()


# Write your code here
@router.get("/movies/", response_model=MovieListResponseSchema)
def get_movies(
db: Session = Depends(get_db),
page: int = Query(1, ge=1),
per_page: int = Query(10, ge=1, le=20),
):
query = db.query(MovieModel)

total_items = query.count()
total_pages = (total_items + per_page - 1) // per_page

if page > total_pages:
raise HTTPException(status_code=404, detail="No movies found.")

movies_query = query.offset((page - 1) * per_page).limit(per_page).all()
movies = [MovieDetailResponseSchema.model_validate(movie) for movie in movies_query]

prev_page = f"/theater/movies/?page={page - 1}&per_page={per_page}" if page > 1 else None
next_page = f"/theater/movies/?page={page + 1}&per_page={per_page}" if page < total_pages else None

return MovieListResponseSchema(
movies=movies,
prev_page=prev_page,
next_page=next_page,
total_pages=total_pages,
total_items=total_items
)


@router.get("/movies/{movie_id}/", response_model=MovieDetailResponseSchema)
def get_movie(movie_id: int, db: Session = Depends(get_db)):
movie = db.query(MovieModel).filter(MovieModel.id == movie_id).first()

if not movie:
raise HTTPException(status_code=404, detail="Movie with the given ID was not found.")

return movie
32 changes: 31 additions & 1 deletion src/schemas/movies.py
Original file line number Diff line number Diff line change
@@ -1 +1,31 @@
# Write your code here
from pydantic import BaseModel
import datetime
from typing import Optional


class MovieDetailResponseSchema(BaseModel):
id: int
name: str
date: datetime.date
score: float
genre: str
overview: str
crew: str
orig_title: str
status: str
orig_lang: str
budget: float
revenue: float
country: str

model_config = {
"from_attributes": True,
}


class MovieListResponseSchema(BaseModel):
movies: list[MovieDetailResponseSchema]
prev_page: Optional[str]
next_page: Optional[str]
total_pages: int
total_items: int

0 comments on commit c32c69f

Please sign in to comment.