updated more docstrings for various controllers; prepped musician tests
This commit is contained in:
@@ -22,8 +22,16 @@ class BaseController:
|
||||
self.MAX_FILE_SIZE = ONE_MB
|
||||
|
||||
async def verify_image(self, file: UploadFile) -> bytes:
|
||||
"""
|
||||
Verifies that the file is an image and is within the maximum file size.
|
||||
"""Verifies that the file is an image and is within the maximum file size.
|
||||
|
||||
Args:
|
||||
file (UploadFile): The file to be verified
|
||||
|
||||
Raises:
|
||||
HTTPException: If the file is not an image or exceeds the maximum file size (status code 400)
|
||||
|
||||
Returns:
|
||||
bytes: The file contents as bytes
|
||||
"""
|
||||
if file.content_type not in self.ALL_FILES:
|
||||
raise HTTPException(
|
||||
@@ -39,8 +47,10 @@ class BaseController:
|
||||
return image_file
|
||||
|
||||
def log_error(self, e: Exception) -> None:
|
||||
"""
|
||||
Logs an error to a timestamped text file in the logs directory.
|
||||
"""Logs an error to a timestamped text file in the logs directory.
|
||||
|
||||
Args:
|
||||
e (Exception): Any exception object
|
||||
"""
|
||||
curr_dir = Path(__file__).parent
|
||||
log_dir = curr_dir / "logs"
|
||||
|
||||
@@ -18,16 +18,19 @@ class EventController(BaseController):
|
||||
Testing: pass a mocked EventQueries object to the constructor.
|
||||
"""
|
||||
|
||||
def __init__(self, eq=event_queries) -> None:
|
||||
def __init__(self, event_queries=event_queries) -> None:
|
||||
super().__init__()
|
||||
self.db: EventQueries = eq
|
||||
self.db: EventQueries = event_queries
|
||||
|
||||
def _all_series(self, data: list[dict]) -> dict[str, EventSeries]:
|
||||
"""
|
||||
Helper method to instantiate EventSeries objects from sql rows (a list of dictionaries).
|
||||
Instantiation is done by destructuring the dictionary into the EventSeries constructor.
|
||||
Should not be called directly; use get_all_series() instead.
|
||||
series.name is a required and unique field and can reliably be used as a key in a dictionary.
|
||||
"""Creates and returns a dictionary of EventSeries objects from a list of sql rows (as dicts).
|
||||
Should only be used internally.
|
||||
|
||||
Args:
|
||||
data (list[dict]): List of dicts, each representing a row from the database. `event_id` may be null
|
||||
|
||||
Returns:
|
||||
dict[str, EventSeries]: A dictionary of EventSeries objects, keyed by series name
|
||||
"""
|
||||
all_series: dict[str, EventSeries] = {}
|
||||
|
||||
@@ -41,12 +44,13 @@ class EventController(BaseController):
|
||||
return all_series
|
||||
|
||||
async def get_all_series(self) -> list[EventSeries]:
|
||||
"""
|
||||
Attempts to create and return a list of EventSeries objects and is consumed by the main controller.
|
||||
Will trigger a 500 status code if any exception is raised, and log the error to a timestamped text file.
|
||||
"""Retrieves all EventSeries objects from the database and returns them as a list.
|
||||
|
||||
The list of EventSeries is created by calling the _all_series() helper method, which provided this data
|
||||
as a list of dicts.
|
||||
Raises:
|
||||
HTTPException: If any error occurs during the retrieval process (status code 500)
|
||||
|
||||
Returns:
|
||||
list[EventSeries]: A list of EventSeries objects which are suitable for a response body
|
||||
"""
|
||||
series_data = await self.db.select_all_series()
|
||||
|
||||
@@ -60,16 +64,25 @@ class EventController(BaseController):
|
||||
)
|
||||
|
||||
async def get_one_series_by_id(self, series_id: int) -> EventSeries:
|
||||
"""Builds and returns a single EventSeries object by its numeric ID.
|
||||
|
||||
Args:
|
||||
series_id (int): The numeric id of the series to retrieve
|
||||
|
||||
Raises:
|
||||
HTTPException: If the series is not found (status code 404)
|
||||
HTTPException: If an error occurs (status code 500)
|
||||
|
||||
Returns:
|
||||
EventSeries: A single EventSeries object
|
||||
"""
|
||||
Builds and returns a single EventSeries object by its numeric ID.
|
||||
"""
|
||||
if not (data := await self.db.select_one_by_id(series_id)):
|
||||
if not (rows := await self.db.select_one_by_id(series_id)):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Event not found"
|
||||
)
|
||||
try:
|
||||
return EventSeries(
|
||||
**data[0], events=[Event(**e) for e in data if e["event_id"]]
|
||||
**rows[0], events=[Event(**row) for row in rows if row.get("event_id")]
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
@@ -78,8 +91,16 @@ class EventController(BaseController):
|
||||
)
|
||||
|
||||
async def create_series(self, series: NewEventSeries) -> EventSeries:
|
||||
"""
|
||||
Takes a NewEventSeries object and passes it to the database layer for insertion.
|
||||
"""Takes a NewEventSeries object and passes it to the database layer for insertion.
|
||||
|
||||
Args:
|
||||
series (NewEventSeries): A NewEventSeries object which does not yet have an ID
|
||||
|
||||
Raises:
|
||||
HTTPException: If the series name already exists (status code 400)
|
||||
|
||||
Returns:
|
||||
EventSeries: The newly created EventSeries object with an ID
|
||||
"""
|
||||
try:
|
||||
inserted_id = await self.db.insert_one_series(series)
|
||||
@@ -92,10 +113,17 @@ class EventController(BaseController):
|
||||
detail=f"Series name already exists. Each series must have a unique name.\n{e}",
|
||||
)
|
||||
|
||||
async def add_series_poster(self, series_id, poster: UploadFile) -> EventSeries:
|
||||
"""
|
||||
Adds (or updates) a poster image to a series.
|
||||
Actual image storage is done with Cloudinary and the public ID is stored in the database.
|
||||
async def add_series_poster(
|
||||
self, series_id: int, poster: UploadFile
|
||||
) -> EventSeries:
|
||||
"""Adds (or updates) a poster image to a series.
|
||||
|
||||
Args:
|
||||
series_id (int): The numeric ID of the series to update
|
||||
poster (UploadFile): The image file to upload
|
||||
|
||||
Returns:
|
||||
EventSeries: The updated EventSeries object
|
||||
"""
|
||||
series = await self.get_one_series_by_id(series_id)
|
||||
series.poster_id = await self._upload_poster(poster)
|
||||
@@ -103,8 +131,17 @@ class EventController(BaseController):
|
||||
return await self.get_one_series_by_id(series.series_id)
|
||||
|
||||
async def _upload_poster(self, poster: UploadFile) -> str:
|
||||
"""
|
||||
Uploads a poster image to Cloudinary and returns the public ID for storage in the database.
|
||||
"""Uploads a poster image to Cloudinary and returns the public ID for storage in the database.
|
||||
Should only be used internally.
|
||||
|
||||
Args:
|
||||
poster (UploadFile): The image file to upload
|
||||
|
||||
Raises:
|
||||
HTTPException: If an error occurs during the upload process (status code 500)
|
||||
|
||||
Returns:
|
||||
str: The public ID of the uploaded image
|
||||
"""
|
||||
image_file = await self.verify_image(poster)
|
||||
try:
|
||||
@@ -117,15 +154,27 @@ class EventController(BaseController):
|
||||
)
|
||||
|
||||
async def delete_series(self, id: int) -> None:
|
||||
"""
|
||||
Ensures an EventSeries object exists and then deletes it from the database
|
||||
"""Ensures an EventSeries object exists and then deletes it from the database.
|
||||
|
||||
Args:
|
||||
id (int): The numeric ID of the series to delete
|
||||
"""
|
||||
series = await self.get_one_series_by_id(id)
|
||||
await self.db.delete_one_series(series)
|
||||
|
||||
async def update_series(self, route_id: int, series: EventSeries) -> EventSeries:
|
||||
"""
|
||||
Updates an existing EventSeries object in the database.
|
||||
"""Updates an existing EventSeries object in the database.
|
||||
|
||||
Args:
|
||||
route_id (int): The numeric ID of the series in the URL
|
||||
series (EventSeries): The updated EventSeries object
|
||||
|
||||
Raises:
|
||||
HTTPException: if the ID in the URL does not match the ID in the request body (status code 400)
|
||||
HTTPException: if the poster ID is updated directly (status code 400)
|
||||
|
||||
Returns:
|
||||
EventSeries: The updated EventSeries object with updated info
|
||||
"""
|
||||
if route_id != series.series_id:
|
||||
raise HTTPException(
|
||||
|
||||
@@ -9,11 +9,27 @@ from app.models.musician import Musician
|
||||
|
||||
|
||||
class MusicianController(BaseController):
|
||||
def __init__(self) -> None:
|
||||
"""
|
||||
Handles all musician-related operations and serves as an intermediate controller between
|
||||
the main controller and the model layer.
|
||||
Inherits from BaseController, which provides logging and other generic methods.
|
||||
|
||||
Testing: pass a mocked MusicianQueries object to the constructor.
|
||||
"""
|
||||
|
||||
def __init__(self, musician_queries=musician_queries) -> None:
|
||||
super().__init__()
|
||||
self.db: MusicianQueries = musician_queries
|
||||
|
||||
async def get_musicians(self) -> list[Musician]:
|
||||
"""Retrieves all musicians from the database and returns them as a list of Musician objects.
|
||||
|
||||
Raises:
|
||||
HTTPException: If any error occurs during the retrieval process (status code 500)
|
||||
|
||||
Returns:
|
||||
list[Musician]: A list of Musician objects which are suitable for a response body
|
||||
"""
|
||||
data = await self.db.select_all_series()
|
||||
try:
|
||||
return [Musician(**m) for m in data]
|
||||
@@ -23,8 +39,20 @@ class MusicianController(BaseController):
|
||||
detail=f"Error creating musician objects: {e}",
|
||||
)
|
||||
|
||||
async def get_musician(self, id: int) -> Musician:
|
||||
if (data := await self.db.select_one_by_id(id)) is None:
|
||||
async def get_musician(self, musician_id: int) -> Musician:
|
||||
"""Retrieves a single musician from the database and returns it as a Musician object.
|
||||
|
||||
Args:
|
||||
id (int): The ID of the musician to retrieve
|
||||
|
||||
Raises:
|
||||
HTTPException: If the musician is not found (status code 404)
|
||||
HTTPException: If any error occurs during the retrieval process (status code 500)
|
||||
|
||||
Returns:
|
||||
Musician: A Musician object which is suitable for a response body
|
||||
"""
|
||||
if (data := await self.db.select_one_by_id(musician_id)) is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Musician not found"
|
||||
)
|
||||
@@ -42,40 +70,91 @@ class MusicianController(BaseController):
|
||||
new_bio: str,
|
||||
file: UploadFile | None = None,
|
||||
) -> Musician:
|
||||
"""Updates a musician's bio and/or headshot by conditionally calling the appropriate methods.
|
||||
|
||||
Args:
|
||||
musician_id (int): The numeric ID of the musician to update
|
||||
new_bio (str): The new biography for the musician
|
||||
file (UploadFile | None, optional): The new headshot file. Defaults to None.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the musician is not found (status code 404)
|
||||
|
||||
Returns:
|
||||
Musician: The updated Musician object
|
||||
"""
|
||||
musician = await self.get_musician(musician_id)
|
||||
if new_bio != musician.bio:
|
||||
return await self.update_musician_bio(musician.id, new_bio)
|
||||
return await self._update_musician_bio(musician.id, new_bio)
|
||||
if file is not None:
|
||||
return await self.upload_headshot(musician.id, file)
|
||||
return await self._upload_headshot(musician.id, file)
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Update operation not implemented. Neither the bio or headshot was updated.",
|
||||
)
|
||||
|
||||
async def update_musician_headshot(self, id: int, headshot_id: str) -> Musician:
|
||||
await self.get_musician(id)
|
||||
async def update_musician_headshot(
|
||||
self, musician_id: int, headshot_id: str
|
||||
) -> Musician:
|
||||
"""Updates a musician's headshot in the database.
|
||||
|
||||
Args:
|
||||
id (int): The numeric ID of the musician to update
|
||||
headshot_id (str): The public ID of the new headshot (as determined by Cloudinary)
|
||||
|
||||
Raises:
|
||||
HTTPException: If any error occurs during the update process (status code 500)
|
||||
|
||||
Returns:
|
||||
Musician: The updated Musician object
|
||||
"""
|
||||
await self.get_musician(musician_id)
|
||||
try:
|
||||
await self.db.update_headshot(id, headshot_id)
|
||||
await self.db.update_headshot(musician_id, headshot_id)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Error updating musician headshot: {e}",
|
||||
)
|
||||
return await self.get_musician(id)
|
||||
return await self.get_musician(musician_id)
|
||||
|
||||
async def update_musician_bio(self, id: int, bio: str) -> Musician:
|
||||
await self.get_musician(id) # Check if musician exists
|
||||
async def _update_musician_bio(self, musician_id: int, bio: str) -> Musician:
|
||||
"""Updates a musician's bio in the database.
|
||||
|
||||
Args:
|
||||
id (int): The numeric ID of the musician to update
|
||||
bio (str): The new biography for the musician
|
||||
|
||||
Raises:
|
||||
HTTPException: If any error occurs during the update process (status code 500)
|
||||
|
||||
Returns:
|
||||
Musician: The updated Musician object
|
||||
"""
|
||||
await self.get_musician(musician_id) # Check if musician exists
|
||||
try:
|
||||
await self.db.update_bio(id, bio)
|
||||
await self.db.update_bio(musician_id, bio)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Error updating musician bio: {e}",
|
||||
)
|
||||
return await self.get_musician(id)
|
||||
return await self.get_musician(musician_id)
|
||||
|
||||
async def upload_headshot(self, id: int, file: UploadFile) -> Musician:
|
||||
async def _upload_headshot(self, id: int, file: UploadFile) -> Musician:
|
||||
"""Uploads a new headshot for a musician and updates the database with the new public ID.
|
||||
|
||||
Args:
|
||||
id (int): The numeric ID of the musician to update
|
||||
file (UploadFile): The new headshot file
|
||||
|
||||
Raises:
|
||||
HTTPException: If the file is not an image or exceeds the maximum file size (status code 400)
|
||||
|
||||
Returns:
|
||||
Musician: The updated Musician object
|
||||
"""
|
||||
image_file = await self.verify_image(file)
|
||||
data = uploader.upload(image_file)
|
||||
public_id = data.get("public_id")
|
||||
|
||||
Reference in New Issue
Block a user