This commit is contained in:
Tyrel Souza 2022-10-14 14:16:52 -04:00
parent a5095d7a4b
commit 4d80cc88e1
No known key found for this signature in database
GPG Key ID: F6582CF1308A2360
5 changed files with 39 additions and 39 deletions

1
app.py
View File

@ -1,6 +1,7 @@
from fastapi import FastAPI from fastapi import FastAPI
from pydantic import BaseModel from pydantic import BaseModel
import uvicorn import uvicorn
from controllers import album from controllers import album
# Initialize the app # Initialize the app

View File

@ -2,8 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException
from fastapi_utils.cbv import cbv from fastapi_utils.cbv import cbv
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from models.album import get_all_albums, create_album, get_album_by_id, update_album, delete_album, AlbumException import models
from models.schemas import Album, CreateAndUpdateAlbum, PaginatedAlbum
from database import get_db from database import get_db
@ -15,42 +14,41 @@ class Albums:
session: Session = Depends(get_db) session: Session = Depends(get_db)
# API to get the list of album info # API to get the list of album info
@router.get("/albums", response_model=PaginatedAlbum) @router.get("/albums", response_model=models.schemas.PaginatedAlbum)
def list_albums(self, limit: int = 10, offset: int = 0): def list_albums(self, limit: int = 10, offset: int = 0):
albums_list = get_all_albums(self.session, limit, offset) albums_list = models.album.get_all_albums(self.session, limit, offset)
response = {"limit": limit, "offset": offset, "data": albums_list} response = {"limit": limit, "offset": offset, "data": albums_list}
return response return response
# API endpoint to add an album to the database # API endpoint to add an album to the database
@router.post("/albums") @router.post("/albums")
def add_album(self, album: CreateAndUpdateAlbum): def add_album(self, album: models.schemas.AlbumBase):
try: try:
album = create_album(self.session, album) album = models.album.create_album(self.session, album)
return album return album
except AlbumException as ex: except models.exceptions.AlbumException as ex:
raise HTTPException(**ex.__dict__) raise HTTPException(**ex.__dict__)
# API endpoint to get info of a particular album # API endpoint to get info of a particular album
@router.get("/albums/{album_id}", response_model=Album) @router.get("/albums/{album_id}", response_model=models.schemas.Album)
def get_album(album_id: int, session: Session = Depends(get_db)): def get_album(album_id: int, session: Session = Depends(get_db)):
try: try:
album = get_album_by_id(session, album_id) album = models.album.get_album_by_id(session, album_id)
return album return album
except AlbumException as ex: except models.exceptions.AlbumException as ex:
raise HTTPException(**ex.__dict__) raise HTTPException(**ex.__dict__)
# API to update a existing album info # API to update a existing album info
@router.put("/albums/{album_id}", response_model=Album) @router.put("/albums/{album_id}", response_model=models.schemas.Album)
def update_album(album_id: int, new_info: CreateAndUpdateAlbum, session: Session = Depends(get_db)): def update_album(album_id: int, new_info: models.schemas.AlbumBase, session: Session = Depends(get_db)):
try: try:
album = update_album(session, album_id, new_info) album = models.album.update_album(session, album_id, new_info)
return album return album
except AlbumException as ex: except models.exceptions.AlbumException as ex:
raise HTTPException(**ex.__dict__) raise HTTPException(**ex.__dict__)
@ -58,6 +56,6 @@ def update_album(album_id: int, new_info: CreateAndUpdateAlbum, session: Session
@router.delete("/albums/{album_id}") @router.delete("/albums/{album_id}")
def delete_album(album_id: int, session: Session = Depends(get_db)): def delete_album(album_id: int, session: Session = Depends(get_db)):
try: try:
return delete_album(session, album_id) return models.album.delete_album(session, album_id)
except AlbumException as ex: except models.exceptions.AlbumException as ex:
raise HTTPException(**ex.__dict__) raise HTTPException(**ex.__dict__)

View File

@ -1,9 +1,12 @@
from sqlalchemy.schema import Column from sqlalchemy.schema import Column
from sqlalchemy.types import String, Integer, Float from sqlalchemy.types import String, Integer, Float
from database import Base
from typing import List from typing import List
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from models.schemas import CreateAndUpdateAlbum
from models import schemas
from database import Base
from models.exceptions import AlbumNotFoundError, AlbumAlreadyExistError
class Album(Base): class Album(Base):
@ -15,22 +18,6 @@ class Album(Base):
price = Column(Float) price = Column(Float)
class AlbumException(Exception):
...
class AlbumNotFoundError(AlbumException):
def __init__(self):
self.status_code = 404
self.detail = "Album Not Found"
class AlbumAlreadyExistError(AlbumException):
def __init__(self):
self.status_code = 409
self.detail = "Album Already Exists"
# Function to get list of album info # Function to get list of album info
def get_all_albums(session: Session, limit: int, offset: int) -> List[Album]: def get_all_albums(session: Session, limit: int, offset: int) -> List[Album]:
return session.query(Album).offset(offset).limit(limit).all() return session.query(Album).offset(offset).limit(limit).all()
@ -47,7 +34,7 @@ def get_album_by_id(session: Session, _id: int) -> Album:
# Function to add a new album info to the database # Function to add a new album info to the database
def create_album(session: Session, album: CreateAndUpdateAlbum) -> Album: def create_album(session: Session, album: schemas.AlbumBase) -> Album:
album_details = session.query(Album).filter(Album.title == album.title, Album.artist == album.artist).first() album_details = session.query(Album).filter(Album.title == album.title, Album.artist == album.artist).first()
if album_details is not None: if album_details is not None:
raise AlbumAlreadyExistError raise AlbumAlreadyExistError
@ -60,7 +47,7 @@ def create_album(session: Session, album: CreateAndUpdateAlbum) -> Album:
# Function to update details of the album # Function to update details of the album
def update_album(session: Session, _id: int, info_update: CreateAndUpdateAlbum) -> Album: def update_album(session: Session, _id: int, info_update: schemas.AlbumBase) -> Album:
album = get_album_by_id(session, _id) album = get_album_by_id(session, _id)
if album is None: if album is None:

14
models/exceptions.py Normal file
View File

@ -0,0 +1,14 @@
class AlbumException(Exception):
...
class AlbumNotFoundError(AlbumException):
def __init__(self):
self.status_code = 404
self.detail = "Album Not Found"
class AlbumAlreadyExistError(AlbumException):
def __init__(self):
self.status_code = 409
self.detail = "Album Already Exists"

View File

@ -3,14 +3,14 @@ from typing import Optional, List
# TO support creation and update APIs # TO support creation and update APIs
class CreateAndUpdateAlbum(BaseModel): class AlbumBase(BaseModel):
title: str title: str
artist: str artist: str
price: float price: float
# TO support list and get APIs # TO support list and get APIs
class Album(CreateAndUpdateAlbum): class Album(AlbumBase):
id: int id: int
class Config: class Config: