paper-dynasty-database/app/routers_v2/rarity.py
Cal Corum 0c042165b7 fix: replace broad except Exception blocks with DoesNotExist (#15)
Replace 71 broad `except Exception` blocks in 19 router files with the
specific `peewee.DoesNotExist` exception. GET endpoints that call
`Model.get_by_id()` now only catch the expected DoesNotExist error,
allowing real DB failures (connection errors, etc.) to propagate as
500s rather than being masked as 404s.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 15:32:53 -06:00

167 lines
5.3 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, Response
from typing import Optional
import logging
import pydantic
from pandas import DataFrame
from ..db_engine import Rarity, model_to_dict, fn, DoesNotExist
from ..dependencies import oauth2_scheme, valid_token
router = APIRouter(
prefix='/api/v2/rarities',
tags=['rarities']
)
class RarityModel(pydantic.BaseModel):
value: int
name: str
color: str
@router.get('')
async def get_rarities(value: Optional[int] = None, name: Optional[str] = None, min_value: Optional[int] = None,
max_value: Optional[int] = None, csv: Optional[bool] = None):
all_rarities = Rarity.select().order_by(Rarity.id)
if all_rarities.count() == 0:
raise HTTPException(status_code=404, detail=f'There are no rarities to filter')
if value is not None:
all_rarities = all_rarities.where(Rarity.value == value)
if name is not None:
all_rarities = all_rarities.where(fn.Lower(Rarity.name) == name.lower())
if min_value is not None:
all_rarities = all_rarities.where(Rarity.value >= min_value)
if max_value is not None:
all_rarities = all_rarities.where(Rarity.value <= max_value)
if all_rarities.count() == 0:
raise HTTPException(status_code=404, detail=f'No rarities found')
if csv:
data_list = [['id', 'value', 'name']]
for line in all_rarities:
data_list.append(
[
line.id, line.value, line.name
]
)
return_val = DataFrame(data_list).to_csv(header=False, index=False)
return Response(content=return_val, media_type='text/csv')
else:
return_val = {'count': all_rarities.count(), 'rarities': []}
for x in all_rarities:
return_val['rarities'].append(model_to_dict(x))
return return_val
@router.get('/{rarity_id}')
async def get_one_rarity(rarity_id, csv: Optional[bool] = False):
try:
this_rarity = Rarity.get_by_id(rarity_id)
except DoesNotExist:
raise HTTPException(status_code=404, detail=f'No rarity found with id {rarity_id}')
if csv:
data_list = [['id', 'value', 'name']]
for line in this_rarity:
data_list.append(
[
line.id, line.value, line.name
]
)
return_val = DataFrame(data_list).to_csv(header=False, index=False)
return Response(content=return_val, media_type='text/csv')
else:
return_val = model_to_dict(this_rarity)
return return_val
@router.post('')
async def post_rarity(rarity: RarityModel, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning('Bad Token: [REDACTED]')
raise HTTPException(
status_code=401,
detail='You are not authorized to post rarities. This event has been logged.'
)
dupe_team = Rarity.get_or_none(Rarity.name)
if dupe_team:
raise HTTPException(status_code=400, detail=f'There is already a rarity using {rarity.name}')
this_rarity = Rarity(
value=rarity.value,
name=rarity.name,
color=rarity.color
)
saved = this_rarity.save()
if saved == 1:
return_val = model_to_dict(this_rarity)
return return_val
else:
raise HTTPException(
status_code=418,
detail='Well slap my ass and call me a teapot; I could not save that rarity'
)
@router.patch('/{rarity_id}')
async def patch_rarity(
rarity_id, value: Optional[int] = None, name: Optional[str] = None, color: Optional[str] = None,
token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning('Bad Token: [REDACTED]')
raise HTTPException(
status_code=401,
detail='You are not authorized to patch rarities. This event has been logged.'
)
try:
this_rarity = Rarity.get_by_id(rarity_id)
except DoesNotExist:
raise HTTPException(status_code=404, detail=f'No rarity found with id {rarity_id}')
if value is not None:
this_rarity.value = value
if name is not None:
this_rarity.name = name
if color is not None:
this_rarity.color = color
if this_rarity.save() == 1:
return_val = model_to_dict(this_rarity)
return return_val
else:
raise HTTPException(
status_code=418,
detail='Well slap my ass and call me a teapot; I could not save that rarity'
)
@router.delete('/{rarity_id}')
async def v1_rarities_delete(rarity_id, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning('Bad Token: [REDACTED]')
raise HTTPException(
status_code=401,
detail='You are not authorized to delete rarities. This event has been logged.'
)
try:
this_rarity = Rarity.get_by_id(rarity_id)
except DoesNotExist:
raise HTTPException(status_code=404, detail=f'No rarity found with id {rarity_id}')
count = this_rarity.delete_instance()
if count == 1:
raise HTTPException(status_code=200, detail=f'Rarity {rarity_id} has been deleted')
else:
raise HTTPException(status_code=500, detail=f'Rarity {rarity_id} was not deleted')