From 28af8826e6dec6b821eb6ddf1e086f19d06798ee Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Tue, 3 Mar 2026 18:34:30 -0600 Subject: [PATCH] fix: replace raise HTTPException(status_code=200) with return statements (#16) Replace 22 instances of semantically incorrect raise HTTPException(status_code=200, detail=...) with plain return {"message": ...} dicts across 16 router files. Co-Authored-By: Claude Sonnet 4.6 --- app/routers_v2/awards.py | 97 ++++++----- app/routers_v2/batstats.py | 244 ++++++++++++++++++++------- app/routers_v2/cards.py | 201 ++++++++++++++--------- app/routers_v2/cardsets.py | 160 +++++++++++------- app/routers_v2/current.py | 88 ++++++---- app/routers_v2/events.py | 115 ++++++++----- app/routers_v2/gamerewards.py | 111 ++++++++----- app/routers_v2/notifications.py | 133 +++++++++------ app/routers_v2/packs.py | 130 +++++++++------ app/routers_v2/packtypes.py | 110 ++++++++----- app/routers_v2/paperdex.py | 119 ++++++++------ app/routers_v2/pitstats.py | 136 +++++++++++---- app/routers_v2/rarity.py | 110 +++++++------ app/routers_v2/results.py | 282 ++++++++++++++++++++++---------- app/routers_v2/rewards.py | 111 +++++++------ app/routers_v2/teams.py | 3 +- 16 files changed, 1374 insertions(+), 776 deletions(-) diff --git a/app/routers_v2/awards.py b/app/routers_v2/awards.py index 6914bfe..9fe24b1 100644 --- a/app/routers_v2/awards.py +++ b/app/routers_v2/awards.py @@ -8,21 +8,18 @@ from ..db_engine import Award, model_to_dict from ..dependencies import oauth2_scheme, valid_token, LOG_DATA, PRIVATE_IN_SCHEMA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/awards', - tags=['awards'] -) +router = APIRouter(prefix="/api/v2/awards", tags=["awards"]) class AwardModel(pydantic.BaseModel): name: str season: int - timing: str = 'In-Season' + timing: str = "In-Season" card_id: Optional[int] = None team_id: Optional[int] = None image: Optional[str] = None @@ -33,15 +30,20 @@ class AwardReturnList(pydantic.BaseModel): awards: list[AwardModel] -@router.get('') +@router.get("") async def get_awards( - name: Optional[str] = None, season: Optional[int] = None, timing: Optional[str] = None, - card_id: Optional[int] = None, team_id: Optional[int] = None, image: Optional[str] = None, - csv: Optional[bool] = None): + name: Optional[str] = None, + season: Optional[int] = None, + timing: Optional[str] = None, + card_id: Optional[int] = None, + team_id: Optional[int] = None, + image: Optional[str] = None, + csv: Optional[bool] = None, +): all_awards = Award.select().order_by(Award.id) if all_awards.count() == 0: - raise HTTPException(status_code=404, detail=f'There are no awards to filter') + raise HTTPException(status_code=404, detail=f"There are no awards to filter") if name is not None: all_awards = all_awards.where(Award.name == name) @@ -57,52 +59,69 @@ async def get_awards( all_awards = all_awards.where(Award.image == image) if csv: - data_list = [['id', 'name', 'season', 'timing', 'card', 'team', 'image']] + data_list = [["id", "name", "season", "timing", "card", "team", "image"]] for line in all_awards: - data_list.append([ - line.id, line.name, line.season, line.timing, line.card, line.team, line.image - ]) + data_list.append( + [ + line.id, + line.name, + line.season, + line.timing, + line.card, + line.team, + line.image, + ] + ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_awards.count(), 'awards': []} + return_val = {"count": all_awards.count(), "awards": []} for x in all_awards: - return_val['awards'].append(model_to_dict(x)) + return_val["awards"].append(model_to_dict(x)) return return_val -@router.get('/{award_id}') +@router.get("/{award_id}") async def get_one_award(award_id, csv: Optional[bool] = None): try: this_award = Award.get_by_id(award_id) except Exception: - raise HTTPException(status_code=404, detail=f'No award found with id {award_id}') + raise HTTPException( + status_code=404, detail=f"No award found with id {award_id}" + ) if csv: data_list = [ - ['id', 'name', 'season', 'timing', 'card', 'team', 'image'], - [this_award.id, this_award.name, this_award.season, this_award.timing, this_award.card, - this_award.team, this_award.image] + ["id", "name", "season", "timing", "card", "team", "image"], + [ + this_award.id, + this_award.name, + this_award.season, + this_award.timing, + this_award.card, + this_award.team, + this_award.image, + ], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_award) return return_val -@router.post('', include_in_schema=PRIVATE_IN_SCHEMA) +@router.post("", include_in_schema=PRIVATE_IN_SCHEMA) async def post_awards(award: AwardModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post awards. This event has been logged.' + detail="You are not authorized to post awards. This event has been logged.", ) this_award = Award( @@ -111,7 +130,7 @@ async def post_awards(award: AwardModel, token: str = Depends(oauth2_scheme)): timing=award.season, card_id=award.card_id, team_id=award.team_id, - image=award.image + image=award.image, ) saved = this_award.save() @@ -121,28 +140,28 @@ async def post_awards(award: AwardModel, token: str = Depends(oauth2_scheme)): else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that roster' + detail="Well slap my ass and call me a teapot; I could not save that roster", ) -@router.delete('/{award_id}', include_in_schema=PRIVATE_IN_SCHEMA) +@router.delete("/{award_id}", include_in_schema=PRIVATE_IN_SCHEMA) async def delete_award(award_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete awards. This event has been logged.' + detail="You are not authorized to delete awards. This event has been logged.", ) try: this_award = Award.get_by_id(award_id) except Exception: - raise HTTPException(status_code=404, detail=f'No award found with id {award_id}') + raise HTTPException( + status_code=404, detail=f"No award found with id {award_id}" + ) count = this_award.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Award {award_id} has been deleted') + return {"message": f"Award {award_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Award {award_id} was not deleted') - - + raise HTTPException(status_code=500, detail=f"Award {award_id} was not deleted") diff --git a/app/routers_v2/batstats.py b/app/routers_v2/batstats.py index 909c9bf..b802c49 100644 --- a/app/routers_v2/batstats.py +++ b/app/routers_v2/batstats.py @@ -10,15 +10,12 @@ from ..db_engine import db, BattingStat, model_to_dict, fn, Card, Player, Curren from ..dependencies import oauth2_scheme, valid_token, LOG_DATA, PRIVATE_IN_SCHEMA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/batstats', - tags=['Pre-Season 7 Batting Stats'] -) +router = APIRouter(prefix="/api/v2/batstats", tags=["Pre-Season 7 Batting Stats"]) class BatStat(pydantic.BaseModel): @@ -55,7 +52,7 @@ class BatStat(pydantic.BaseModel): csc: Optional[int] = 0 week: int season: int - created: Optional[int] = int(datetime.timestamp(datetime.now())*1000) + created: Optional[int] = int(datetime.timestamp(datetime.now()) * 1000) game_id: int @@ -68,10 +65,19 @@ class BatStatReturnList(pydantic.BaseModel): stats: list[BatStat] -@router.get('', response_model=BatStatReturnList) +@router.get("", response_model=BatStatReturnList) async def get_batstats( - card_id: int = None, player_id: int = None, team_id: int = None, vs_team_id: int = None, week: int = None, - season: int = None, week_start: int = None, week_end: int = None, created: int = None, csv: bool = None): + card_id: int = None, + player_id: int = None, + team_id: int = None, + vs_team_id: int = None, + week: int = None, + season: int = None, + week_start: int = None, + week_end: int = None, + created: int = None, + csv: bool = None, +): all_stats = BattingStat.select().join(Card).join(Player).order_by(BattingStat.id) if season is not None: @@ -104,40 +110,118 @@ async def get_batstats( # raise HTTPException(status_code=404, detail=f'No batting stats found') if csv: - data_list = [['id', 'card_id', 'player_id', 'cardset', 'team', 'vs_team', 'pos', 'pa', 'ab', 'run', 'hit', 'rbi', 'double', - 'triple', 'hr', 'bb', 'so', 'hbp', 'sac', 'ibb', 'gidp', 'sb', 'cs', 'bphr', 'bpfo', 'bp1b', - 'bplo', 'xch', 'xhit', 'error', 'pb', 'sbc', 'csc', 'week', 'season', 'created', 'game_id', 'roster_num']] + data_list = [ + [ + "id", + "card_id", + "player_id", + "cardset", + "team", + "vs_team", + "pos", + "pa", + "ab", + "run", + "hit", + "rbi", + "double", + "triple", + "hr", + "bb", + "so", + "hbp", + "sac", + "ibb", + "gidp", + "sb", + "cs", + "bphr", + "bpfo", + "bp1b", + "bplo", + "xch", + "xhit", + "error", + "pb", + "sbc", + "csc", + "week", + "season", + "created", + "game_id", + "roster_num", + ] + ] for line in all_stats: data_list.append( [ - line.id, line.card.id, line.card.player.player_id, line.card.player.cardset.name, line.team.abbrev, line.vs_team.abbrev, - line.pos, line.pa, line.ab, line.run, line.hit, line.rbi, line.double, line.triple, line.hr, - line.bb, line.so, line.hbp, line.sac, line.ibb, line.gidp, line.sb, line.cs, line.bphr, line.bpfo, - line.bp1b, line.bplo, line.xch, line.xhit, line.error, line.pb, line.sbc, line.csc, line.week, - line.season, line.created, line.game_id, line.roster_num + line.id, + line.card.id, + line.card.player.player_id, + line.card.player.cardset.name, + line.team.abbrev, + line.vs_team.abbrev, + line.pos, + line.pa, + line.ab, + line.run, + line.hit, + line.rbi, + line.double, + line.triple, + line.hr, + line.bb, + line.so, + line.hbp, + line.sac, + line.ibb, + line.gidp, + line.sb, + line.cs, + line.bphr, + line.bpfo, + line.bp1b, + line.bplo, + line.xch, + line.xhit, + line.error, + line.pb, + line.sbc, + line.csc, + line.week, + line.season, + line.created, + line.game_id, + line.roster_num, ] ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_stats.count(), 'stats': []} + return_val = {"count": all_stats.count(), "stats": []} for x in all_stats: - return_val['stats'].append(model_to_dict(x, recurse=False)) + return_val["stats"].append(model_to_dict(x, recurse=False)) return return_val -@router.get('/player/{player_id}', response_model=BatStat) +@router.get("/player/{player_id}", response_model=BatStat) async def get_player_stats( - player_id: int, team_id: int = None, vs_team_id: int = None, week_start: int = None, week_end: int = None, - csv: bool = None): - all_stats = (BattingStat - .select(fn.COUNT(BattingStat.created).alias('game_count')) - .join(Card) - .group_by(BattingStat.card) - .where(BattingStat.card.player == player_id)).scalar() + player_id: int, + team_id: int = None, + vs_team_id: int = None, + week_start: int = None, + week_end: int = None, + csv: bool = None, +): + all_stats = ( + BattingStat.select(fn.COUNT(BattingStat.created).alias("game_count")) + .join(Card) + .group_by(BattingStat.card) + .where(BattingStat.card.player == player_id) + ).scalar() if team_id is not None: all_stats = all_stats.where(BattingStat.team_id == team_id) @@ -151,37 +235,82 @@ async def get_player_stats( if csv: data_list = [ [ - 'pa', 'ab', 'run', 'hit', 'rbi', 'double', 'triple', 'hr', 'bb', 'so', 'hbp', 'sac', 'ibb', 'gidp', - 'sb', 'cs', 'bphr', 'bpfo', 'bp1b', 'bplo', 'xch', 'xhit', 'error', 'pb', 'sbc', 'csc', - ],[ - all_stats.pa_sum, all_stats.ab_sum, all_stats.run, all_stats.hit_sum, all_stats.rbi_sum, - all_stats.double_sum, all_stats.triple_sum, all_stats.hr_sum, all_stats.bb_sum, all_stats.so_sum, - all_stats.hbp_sum, all_stats.sac, all_stats.ibb_sum, all_stats.gidp_sum, all_stats.sb_sum, - all_stats.cs_sum, all_stats.bphr_sum, all_stats.bpfo_sum, all_stats.bp1b_sum, all_stats.bplo_sum, - all_stats.xch, all_stats.xhit_sum, all_stats.error_sum, all_stats.pb_sum, all_stats.sbc_sum, - all_stats.csc_sum - ] + "pa", + "ab", + "run", + "hit", + "rbi", + "double", + "triple", + "hr", + "bb", + "so", + "hbp", + "sac", + "ibb", + "gidp", + "sb", + "cs", + "bphr", + "bpfo", + "bp1b", + "bplo", + "xch", + "xhit", + "error", + "pb", + "sbc", + "csc", + ], + [ + all_stats.pa_sum, + all_stats.ab_sum, + all_stats.run, + all_stats.hit_sum, + all_stats.rbi_sum, + all_stats.double_sum, + all_stats.triple_sum, + all_stats.hr_sum, + all_stats.bb_sum, + all_stats.so_sum, + all_stats.hbp_sum, + all_stats.sac, + all_stats.ibb_sum, + all_stats.gidp_sum, + all_stats.sb_sum, + all_stats.cs_sum, + all_stats.bphr_sum, + all_stats.bpfo_sum, + all_stats.bp1b_sum, + all_stats.bplo_sum, + all_stats.xch, + all_stats.xhit_sum, + all_stats.error_sum, + all_stats.pb_sum, + all_stats.sbc_sum, + all_stats.csc_sum, + ], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - logging.debug(f'stat pull query: {all_stats}\n') + logging.debug(f"stat pull query: {all_stats}\n") # logging.debug(f'result 0: {all_stats[0]}\n') for x in all_stats: - logging.debug(f'this_line: {model_to_dict(x)}') + logging.debug(f"this_line: {model_to_dict(x)}") return_val = model_to_dict(all_stats[0]) return return_val -@router.post('', include_in_schema=PRIVATE_IN_SCHEMA) +@router.post("", include_in_schema=PRIVATE_IN_SCHEMA) async def post_batstats(stats: BattingStatModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post stats. This event has been logged.' + detail="You are not authorized to post stats. This event has been logged.", ) new_stats = [] @@ -220,36 +349,40 @@ async def post_batstats(stats: BattingStatModel, token: str = Depends(oauth2_sch csc=x.csc, week=x.week, season=x.season, - created=datetime.fromtimestamp(x.created / 1000) if x.created else datetime.now(), - game_id=x.game_id + created=( + datetime.fromtimestamp(x.created / 1000) + if x.created + else datetime.now() + ), + game_id=x.game_id, ) new_stats.append(this_stat) with db.atomic(): BattingStat.bulk_create(new_stats, batch_size=15) - raise HTTPException(status_code=200, detail=f'{len(new_stats)} batting lines have been added') + return {"message": f"{len(new_stats)} batting lines have been added"} -@router.delete('/{stat_id}', include_in_schema=PRIVATE_IN_SCHEMA) +@router.delete("/{stat_id}", include_in_schema=PRIVATE_IN_SCHEMA) async def delete_batstat(stat_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete stats. This event has been logged.' + detail="You are not authorized to delete stats. This event has been logged.", ) try: this_stat = BattingStat.get_by_id(stat_id) except Exception: - raise HTTPException(status_code=404, detail=f'No stat found with id {stat_id}') + raise HTTPException(status_code=404, detail=f"No stat found with id {stat_id}") count = this_stat.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Stat {stat_id} has been deleted') + return {"message": f"Stat {stat_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Stat {stat_id} was not deleted') + raise HTTPException(status_code=500, detail=f"Stat {stat_id} was not deleted") # @app.get('/api/v1/plays/batting') @@ -454,4 +587,3 @@ async def delete_batstat(stat_id, token: str = Depends(oauth2_scheme)): # } # db.close() # return return_stats - diff --git a/app/routers_v2/cards.py b/app/routers_v2/cards.py index ca294ff..f4a0dd1 100644 --- a/app/routers_v2/cards.py +++ b/app/routers_v2/cards.py @@ -8,15 +8,12 @@ from ..db_engine import db, Card, model_to_dict, Team, Player, Pack, Paperdex, C from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/cards', - tags=['cards'] -) +router = APIRouter(prefix="/api/v2/cards", tags=["cards"]) class CardPydantic(pydantic.BaseModel): @@ -31,12 +28,20 @@ class CardModel(pydantic.BaseModel): cards: List[CardPydantic] -@router.get('') +@router.get("") async def get_cards( - player_id: Optional[int] = None, team_id: Optional[int] = None, pack_id: Optional[int] = None, - value: Optional[int] = None, min_value: Optional[int] = None, max_value: Optional[int] = None, variant: Optional[int] = None, - order_by: Optional[str] = None, limit: Optional[int] = None, dupes: Optional[bool] = None, - csv: Optional[bool] = None): + player_id: Optional[int] = None, + team_id: Optional[int] = None, + pack_id: Optional[int] = None, + value: Optional[int] = None, + min_value: Optional[int] = None, + max_value: Optional[int] = None, + variant: Optional[int] = None, + order_by: Optional[str] = None, + limit: Optional[int] = None, + dupes: Optional[bool] = None, + csv: Optional[bool] = None, +): all_cards = Card.select() # if all_cards.count() == 0: @@ -47,19 +52,25 @@ async def get_cards( try: this_team = Team.get_by_id(team_id) except Exception: - raise HTTPException(status_code=404, detail=f'No team found with id {team_id}') + raise HTTPException( + status_code=404, detail=f"No team found with id {team_id}" + ) all_cards = all_cards.where(Card.team == this_team) if player_id is not None: try: this_player = Player.get_by_id(player_id) except Exception: - raise HTTPException(status_code=404, detail=f'No player found with id {player_id}') + raise HTTPException( + status_code=404, detail=f"No player found with id {player_id}" + ) all_cards = all_cards.where(Card.player == this_player) if pack_id is not None: try: this_pack = Pack.get_by_id(pack_id) except Exception: - raise HTTPException(status_code=404, detail=f'No pack found with id {pack_id}') + raise HTTPException( + status_code=404, detail=f"No pack found with id {pack_id}" + ) all_cards = all_cards.where(Card.pack == this_pack) if value is not None: all_cards = all_cards.where(Card.value == value) @@ -70,7 +81,7 @@ async def get_cards( if max_value is not None: all_cards = all_cards.where(Card.value <= max_value) if order_by is not None: - if order_by.lower() == 'new': + if order_by.lower() == "new": all_cards = all_cards.order_by(-Card.id) else: all_cards = all_cards.order_by(Card.id) @@ -78,8 +89,10 @@ async def get_cards( all_cards = all_cards.limit(limit) if dupes: if team_id is None: - raise HTTPException(status_code=400, detail='Dupe checking must include a team_id') - logging.debug(f'dupe check') + raise HTTPException( + status_code=400, detail="Dupe checking must include a team_id" + ) + logging.debug(f"dupe check") p_query = Card.select(Card.player).where(Card.team_id == team_id) seen = set() dupes = [] @@ -95,65 +108,83 @@ async def get_cards( # raise HTTPException(status_code=404, detail=f'No cards found') if csv: - data_list = [['id', 'player', 'cardset', 'rarity', 'team', 'pack', 'value']] #, 'variant']] + data_list = [ + ["id", "player", "cardset", "rarity", "team", "pack", "value"] + ] # , 'variant']] for line in all_cards: data_list.append( [ - line.id, line.player.p_name, line.player.cardset, line.player.rarity, line.team.abbrev, line.pack, + line.id, + line.player.p_name, + line.player.cardset, + line.player.rarity, + line.team.abbrev, + line.pack, line.value, # line.variant ] ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_cards.count(), 'cards': []} + return_val = {"count": all_cards.count(), "cards": []} for x in all_cards: this_record = model_to_dict(x) - logging.debug(f'this_record: {this_record}') + logging.debug(f"this_record: {this_record}") this_dex = Paperdex.select().where(Paperdex.player == x) - this_record['player']['paperdex'] = {'count': this_dex.count(), 'paperdex': []} + this_record["player"]["paperdex"] = { + "count": this_dex.count(), + "paperdex": [], + } for y in this_dex: - this_record['player']['paperdex']['paperdex'].append(model_to_dict(y, recurse=False)) + this_record["player"]["paperdex"]["paperdex"].append( + model_to_dict(y, recurse=False) + ) - return_val['cards'].append(this_record) + return_val["cards"].append(this_record) # return_val['cards'].append(model_to_dict(x)) return return_val -@router.get('/{card_id}') +@router.get("/{card_id}") async def v1_cards_get_one(card_id, csv: Optional[bool] = False): try: this_card = Card.get_by_id(card_id) except Exception: - raise HTTPException(status_code=404, detail=f'No card found with id {card_id}') + raise HTTPException(status_code=404, detail=f"No card found with id {card_id}") if csv: data_list = [ - ['id', 'player', 'team', 'pack', 'value'], - [this_card.id, this_card.player, this_card.team.abbrev, this_card.pack, this_card.value] + ["id", "player", "team", "pack", "value"], + [ + this_card.id, + this_card.player, + this_card.team.abbrev, + this_card.pack, + this_card.value, + ], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_card) return return_val -@router.post('') +@router.post("") async def v1_cards_post(cards: CardModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post cards. This event has been logged.' + detail="You are not authorized to post cards. This event has been logged.", ) last_card = Card.select(Card.id).order_by(-Card.id).limit(1) lc_id = last_card[0].id @@ -162,7 +193,7 @@ async def v1_cards_post(cards: CardModel, token: str = Depends(oauth2_scheme)): player_ids = [] inc_dex = True this_team = Team.get_by_id(cards.cards[0].team_id) - if this_team.is_ai or 'Gauntlet' in this_team.abbrev: + if this_team.is_ai or "Gauntlet" in this_team.abbrev: inc_dex = False # new_dex = [] @@ -182,11 +213,13 @@ async def v1_cards_post(cards: CardModel, token: str = Depends(oauth2_scheme)): with db.atomic(): Card.bulk_create(new_cards, batch_size=15) - cost_query = Player.update(cost=Player.cost + 1).where(Player.player_id << player_ids) + cost_query = Player.update(cost=Player.cost + 1).where( + Player.player_id << player_ids + ) cost_query.execute() # sheets.post_new_cards(SHEETS_AUTH, lc_id) - raise HTTPException(status_code=200, detail=f'{len(new_cards)} cards have been added') + return {"message": f"{len(new_cards)} cards have been added"} # @router.post('/ai-update') @@ -203,21 +236,27 @@ async def v1_cards_post(cards: CardModel, token: str = Depends(oauth2_scheme)): # raise HTTPException(status_code=200, detail=f'Just sent AI cards to sheets') -@router.post('/legal-check/{rarity_name}') +@router.post("/legal-check/{rarity_name}") async def v1_cards_legal_check( - rarity_name: str, card_id: list = Query(default=None), token: str = Depends(oauth2_scheme)): + rarity_name: str, + card_id: list = Query(default=None), + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') - raise HTTPException( - status_code=401, - detail='Unauthorized' - ) + logging.warning(f"Bad Token: {token}") + raise HTTPException(status_code=401, detail="Unauthorized") if rarity_name not in CARDSETS.keys(): - return f'Rarity name {rarity_name} not a valid check' + return f"Rarity name {rarity_name} not a valid check" # Handle case where card_id is passed as a stringified list - if card_id and len(card_id) == 1 and isinstance(card_id[0], str) and card_id[0].startswith('['): + if ( + card_id + and len(card_id) == 1 + and isinstance(card_id[0], str) + and card_id[0].startswith("[") + ): import ast + try: card_id = [int(x) for x in ast.literal_eval(card_id[0])] except (ValueError, SyntaxError): @@ -227,75 +266,83 @@ async def v1_cards_legal_check( all_cards = Card.select().where(Card.id << card_id) for x in all_cards: - if x.player.cardset_id not in CARDSETS[rarity_name]['human']: + if x.player.cardset_id not in CARDSETS[rarity_name]["human"]: if x.player.p_name in x.player.description: bad_cards.append(x.player.description) else: - bad_cards.append(f'{x.player.description} {x.player.p_name}') + bad_cards.append(f"{x.player.description} {x.player.p_name}") - return {'count': len(bad_cards), 'bad_cards': bad_cards} + return {"count": len(bad_cards), "bad_cards": bad_cards} -@router.post('/post-update/{starting_id}') +@router.post("/post-update/{starting_id}") async def v1_cards_post_update(starting_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to update card lists. This event has been logged.' + detail="You are not authorized to update card lists. This event has been logged.", ) # sheets.post_new_cards(SHEETS_AUTH, starting_id) - raise HTTPException(status_code=200, detail=f'Just sent cards to sheets starting at ID {starting_id}') + return {"message": f"Just sent cards to sheets starting at ID {starting_id}"} -@router.post('/post-delete') +@router.post("/post-delete") async def v1_cards_post_delete(del_ids: str, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete card lists. This event has been logged.' + detail="You are not authorized to delete card lists. This event has been logged.", ) - logging.info(f'del_ids: {del_ids} / type: {type(del_ids)}') + logging.info(f"del_ids: {del_ids} / type: {type(del_ids)}") # sheets.post_deletion(SHEETS_AUTH, del_ids.split(',')) -@router.post('/wipe-team/{team_id}') +@router.post("/wipe-team/{team_id}") async def v1_cards_wipe_team(team_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to wipe teams. This event has been logged.' + detail="You are not authorized to wipe teams. This event has been logged.", ) try: this_team = Team.get_by_id(team_id) except Exception as e: - logging.error(f'/cards/wipe-team/{team_id} - could not find team') - raise HTTPException(status_code=404, detail=f'Team {team_id} not found') + logging.error(f"/cards/wipe-team/{team_id} - could not find team") + raise HTTPException(status_code=404, detail=f"Team {team_id} not found") t_query = Card.update(team=None).where(Card.team == this_team).execute() - return f'Wiped {t_query} cards' + return f"Wiped {t_query} cards" -@router.patch('/{card_id}') +@router.patch("/{card_id}") async def v1_cards_patch( - card_id, player_id: Optional[int] = None, team_id: Optional[int] = None, pack_id: Optional[int] = None, - value: Optional[int] = None, variant: Optional[int] = None, roster1_id: Optional[int] = None, roster2_id: Optional[int] = None, - roster3_id: Optional[int] = None, token: str = Depends(oauth2_scheme)): + card_id, + player_id: Optional[int] = None, + team_id: Optional[int] = None, + pack_id: Optional[int] = None, + value: Optional[int] = None, + variant: Optional[int] = None, + roster1_id: Optional[int] = None, + roster2_id: Optional[int] = None, + roster3_id: Optional[int] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch cards. This event has been logged.' + detail="You are not authorized to patch cards. This event has been logged.", ) try: this_card = Card.get_by_id(card_id) except Exception: - raise HTTPException(status_code=404, detail=f'No card found with id {card_id}') + raise HTTPException(status_code=404, detail=f"No card found with id {card_id}") if player_id is not None: this_card.player_id = player_id @@ -323,26 +370,26 @@ async def v1_cards_patch( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that rarity' + detail="Well slap my ass and call me a teapot; I could not save that rarity", ) -@router.delete('/{card_id}') +@router.delete("/{card_id}") async def v1_cards_delete(card_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete packs. This event has been logged.' + detail="You are not authorized to delete packs. This event has been logged.", ) try: this_card = Card.get_by_id(card_id) except Exception: - raise HTTPException(status_code=404, detail=f'No cards found with id {card_id}') + raise HTTPException(status_code=404, detail=f"No cards found with id {card_id}") count = this_card.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Card {card_id} has been deleted') + return {"message": f"Card {card_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Card {card_id} was not deleted') + raise HTTPException(status_code=500, detail=f"Card {card_id} was not deleted") diff --git a/app/routers_v2/cardsets.py b/app/routers_v2/cardsets.py index 8052264..549a61e 100644 --- a/app/routers_v2/cardsets.py +++ b/app/routers_v2/cardsets.py @@ -8,15 +8,12 @@ from ..db_engine import Cardset, model_to_dict, fn, Event from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/cardsets', - tags=['cardsets'] -) +router = APIRouter(prefix="/api/v2/cardsets", tags=["cardsets"]) class CardsetModel(pydantic.BaseModel): @@ -29,64 +26,91 @@ class CardsetModel(pydantic.BaseModel): ranked_legal: Optional[bool] = True -@router.get('') +@router.get("") async def get_cardsets( - name: Optional[str] = None, in_desc: Optional[str] = None, event_id: Optional[int] = None, - in_packs: Optional[bool] = None, ranked_legal: Optional[bool] = None, csv: Optional[bool] = None): + name: Optional[str] = None, + in_desc: Optional[str] = None, + event_id: Optional[int] = None, + in_packs: Optional[bool] = None, + ranked_legal: Optional[bool] = None, + csv: Optional[bool] = None, +): all_cardsets = Cardset.select().order_by(Cardset.id) if all_cardsets.count() == 0: - raise HTTPException(status_code=404, detail=f'There are no cardsets to filter') + raise HTTPException(status_code=404, detail=f"There are no cardsets to filter") if name is not None: all_cardsets = all_cardsets.where(fn.Lower(Cardset.name) == name.lower()) if in_desc is not None: - all_cardsets = all_cardsets.where(fn.Lower(Cardset.description).contains(in_desc.lower())) + all_cardsets = all_cardsets.where( + fn.Lower(Cardset.description).contains(in_desc.lower()) + ) if event_id is not None: try: this_event = Event.get_by_id(event_id) all_cardsets = all_cardsets.where(Cardset.event == this_event) except Exception as e: - logging.error(f'Failed to find event {event_id}: {e}') - raise HTTPException(status_code=404, detail=f'Event id {event_id} not found') + logging.error(f"Failed to find event {event_id}: {e}") + raise HTTPException( + status_code=404, detail=f"Event id {event_id} not found" + ) if in_packs is not None: all_cardsets = all_cardsets.where(Cardset.in_packs == in_packs) if ranked_legal is not None: all_cardsets = all_cardsets.where(Cardset.ranked_legal == ranked_legal) if all_cardsets.count() == 0: - raise HTTPException(status_code=404, detail=f'No cardsets found') + raise HTTPException(status_code=404, detail=f"No cardsets found") if csv: - data_list = [[ - 'id', 'name', 'description', 'event_id', 'in_packs', 'for_purchase', 'total_cards', 'ranked_legal' - ]] + data_list = [ + [ + "id", + "name", + "description", + "event_id", + "in_packs", + "for_purchase", + "total_cards", + "ranked_legal", + ] + ] for line in all_cardsets: data_list.append( [ - line.id, line.name, line.description, line.event.id if line.event else '', line.in_packs, - line.for_purchase, line.total_cards, line.ranked_legal + line.id, + line.name, + line.description, + line.event.id if line.event else "", + line.in_packs, + line.for_purchase, + line.total_cards, + line.ranked_legal, ] ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_cardsets.count(), 'cardsets': []} + return_val = {"count": all_cardsets.count(), "cardsets": []} for x in all_cardsets: - return_val['cardsets'].append(model_to_dict(x)) + return_val["cardsets"].append(model_to_dict(x)) return return_val -@router.get('/search') +@router.get("/search") async def search_cardsets( - q: str = Query(..., description="Search query for cardset name"), - in_packs: Optional[bool] = None, - ranked_legal: Optional[bool] = None, - event_id: Optional[int] = None, - limit: int = Query(default=25, ge=1, le=100, description="Maximum number of results to return")): + q: str = Query(..., description="Search query for cardset name"), + in_packs: Optional[bool] = None, + ranked_legal: Optional[bool] = None, + event_id: Optional[int] = None, + limit: int = Query( + default=25, ge=1, le=100, description="Maximum number of results to return" + ), +): """ Real-time fuzzy search for cardsets by name. @@ -110,8 +134,10 @@ async def search_cardsets( this_event = Event.get_by_id(event_id) all_cardsets = all_cardsets.where(Cardset.event == this_event) except Exception as e: - logging.error(f'Failed to find event {event_id}: {e}') - raise HTTPException(status_code=404, detail=f'Event id {event_id} not found') + logging.error(f"Failed to find event {event_id}: {e}") + raise HTTPException( + status_code=404, detail=f"Event id {event_id} not found" + ) # Convert to list for sorting cardsets_list = list(all_cardsets) @@ -143,46 +169,50 @@ async def search_cardsets( # Build response return_val = { - 'count': len(limited_results), - 'total_matches': total_matches, - 'cardsets': [model_to_dict(x) for x in limited_results] + "count": len(limited_results), + "total_matches": total_matches, + "cardsets": [model_to_dict(x) for x in limited_results], } return return_val -@router.get('/{cardset_id}') +@router.get("/{cardset_id}") async def get_one_cardset(cardset_id, csv: Optional[bool] = False): try: this_cardset = Cardset.get_by_id(cardset_id) except Exception: - raise HTTPException(status_code=404, detail=f'No cardset found with id {cardset_id}') + raise HTTPException( + status_code=404, detail=f"No cardset found with id {cardset_id}" + ) if csv: data_list = [ - ['id', 'name', 'description'], - [this_cardset.id, this_cardset.name, this_cardset.description] + ["id", "name", "description"], + [this_cardset.id, this_cardset.name, this_cardset.description], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_cardset) return return_val -@router.post('') +@router.post("") async def post_cardsets(cardset: CardsetModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post cardsets. This event has been logged.' + detail="You are not authorized to post cardsets. This event has been logged.", ) dupe_set = Cardset.get_or_none(Cardset.name == cardset.name) if dupe_set: - raise HTTPException(status_code=400, detail=f'There is already a cardset using {cardset.name}') + raise HTTPException( + status_code=400, detail=f"There is already a cardset using {cardset.name}" + ) this_cardset = Cardset(**cardset.__dict__) @@ -193,25 +223,33 @@ async def post_cardsets(cardset: CardsetModel, token: str = Depends(oauth2_schem else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that cardset' + detail="Well slap my ass and call me a teapot; I could not save that cardset", ) -@router.patch('/{cardset_id}') +@router.patch("/{cardset_id}") async def patch_cardsets( - cardset_id, name: Optional[str] = None, description: Optional[str] = None, in_packs: Optional[bool] = None, - for_purchase: Optional[bool] = None, total_cards: Optional[int] = None, ranked_legal: Optional[bool] = None, - token: str = Depends(oauth2_scheme)): + cardset_id, + name: Optional[str] = None, + description: Optional[str] = None, + in_packs: Optional[bool] = None, + for_purchase: Optional[bool] = None, + total_cards: Optional[int] = None, + ranked_legal: Optional[bool] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch cardsets. This event has been logged.' + detail="You are not authorized to patch cardsets. This event has been logged.", ) try: this_cardset = Cardset.get_by_id(cardset_id) except Exception: - raise HTTPException(status_code=404, detail=f'No cardset found with id {cardset_id}') + raise HTTPException( + status_code=404, detail=f"No cardset found with id {cardset_id}" + ) if name is not None: this_cardset.name = name @@ -232,28 +270,30 @@ async def patch_cardsets( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that rarity' + detail="Well slap my ass and call me a teapot; I could not save that rarity", ) -@router.delete('/{cardset_id}') +@router.delete("/{cardset_id}") async def delete_cardsets(cardset_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete cardsets. This event has been logged.' + detail="You are not authorized to delete cardsets. This event has been logged.", ) try: this_cardset = Cardset.get_by_id(cardset_id) except Exception: - raise HTTPException(status_code=404, detail=f'No cardset found with id {cardset_id}') + raise HTTPException( + status_code=404, detail=f"No cardset found with id {cardset_id}" + ) count = this_cardset.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Cardset {cardset_id} has been deleted') + return {"message": f"Cardset {cardset_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Cardset {cardset_id} was not deleted') - - + raise HTTPException( + status_code=500, detail=f"Cardset {cardset_id} was not deleted" + ) diff --git a/app/routers_v2/current.py b/app/routers_v2/current.py index 9a68029..55c9490 100644 --- a/app/routers_v2/current.py +++ b/app/routers_v2/current.py @@ -8,15 +8,12 @@ from ..db_engine import Current, model_to_dict from ..dependencies import oauth2_scheme, valid_token, LOG_DATA, PRIVATE_IN_SCHEMA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/current', - tags=['current'] -) +router = APIRouter(prefix="/api/v2/current", tags=["current"]) class CurrentModel(pydantic.BaseModel): @@ -26,7 +23,7 @@ class CurrentModel(pydantic.BaseModel): gsheet_version: str -@router.get('') +@router.get("") async def get_current(season: Optional[int] = None, csv: Optional[bool] = False): if season: current = Current.get_or_none(season=season) @@ -35,55 +32,60 @@ async def get_current(season: Optional[int] = None, csv: Optional[bool] = False) if csv: current_list = [ - ['id', 'season', 'week'], - [current.id, current.season, current.week] + ["id", "season", "week"], + [current.id, current.season, current.week], ] return_val = DataFrame(current_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(current) return return_val -@router.get('/{current_id}', include_in_schema=PRIVATE_IN_SCHEMA) +@router.get("/{current_id}", include_in_schema=PRIVATE_IN_SCHEMA) async def get_one_current(current_id, csv: Optional[bool] = False): try: current = Current.get_by_id(current_id) except Exception: - raise HTTPException(status_code=404, detail=f'No current found with id {current_id}') + raise HTTPException( + status_code=404, detail=f"No current found with id {current_id}" + ) if csv: current_list = [ - ['id', 'season', 'week'], - [current.id, current.season, current.week] + ["id", "season", "week"], + [current.id, current.season, current.week], ] return_val = DataFrame(current_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(current) return return_val -@router.post('', include_in_schema=PRIVATE_IN_SCHEMA) +@router.post("", include_in_schema=PRIVATE_IN_SCHEMA) async def post_current(current: CurrentModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post current. This event has been logged.' + detail="You are not authorized to post current. This event has been logged.", ) dupe_curr = Current.get_or_none(Current.season == current.season) if dupe_curr: - raise HTTPException(status_code=400, detail=f'There is already a current for season {current.season}') + raise HTTPException( + status_code=400, + detail=f"There is already a current for season {current.season}", + ) this_curr = Current( season=current.season, week=current.week, gsheet_template=current.gsheet_template, - gsheet_version=current.gsheet_version + gsheet_version=current.gsheet_version, ) saved = this_curr.save() @@ -91,24 +93,34 @@ async def post_current(current: CurrentModel, token: str = Depends(oauth2_scheme return_val = model_to_dict(this_curr) return return_val else: - raise HTTPException(status_code=418, detail='Well slap my ass and call me a teapot; I could not save that team') + raise HTTPException( + status_code=418, + detail="Well slap my ass and call me a teapot; I could not save that team", + ) -@router.patch('/{current_id}', include_in_schema=PRIVATE_IN_SCHEMA) +@router.patch("/{current_id}", include_in_schema=PRIVATE_IN_SCHEMA) async def patch_current( - current_id: int, season: Optional[int] = None, week: Optional[int] = None, - gsheet_template: Optional[str] = None, gsheet_version: Optional[str] = None, - live_scoreboard: Optional[int] = None, token: str = Depends(oauth2_scheme)): + current_id: int, + season: Optional[int] = None, + week: Optional[int] = None, + gsheet_template: Optional[str] = None, + gsheet_version: Optional[str] = None, + live_scoreboard: Optional[int] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch current. This event has been logged.' + detail="You are not authorized to patch current. This event has been logged.", ) try: current = Current.get_by_id(current_id) except Exception: - raise HTTPException(status_code=404, detail=f'No current found with id {current_id}') + raise HTTPException( + status_code=404, detail=f"No current found with id {current_id}" + ) if season is not None: current.season = season @@ -127,26 +139,30 @@ async def patch_current( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that current' + detail="Well slap my ass and call me a teapot; I could not save that current", ) -@router.delete('/{current_id}', include_in_schema=PRIVATE_IN_SCHEMA) +@router.delete("/{current_id}", include_in_schema=PRIVATE_IN_SCHEMA) async def delete_current(current_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete current. This event has been logged.' + detail="You are not authorized to delete current. This event has been logged.", ) try: this_curr = Current.get_by_id(current_id) except Exception: - raise HTTPException(status_code=404, detail=f'No current found with id {current_id}') + raise HTTPException( + status_code=404, detail=f"No current found with id {current_id}" + ) count = this_curr.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Current {current_id} has been deleted') + return {"message": f"Current {current_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Current {current_id} was not deleted') + raise HTTPException( + status_code=500, detail=f"Current {current_id} was not deleted" + ) diff --git a/app/routers_v2/events.py b/app/routers_v2/events.py index 6908170..0a48b1e 100644 --- a/app/routers_v2/events.py +++ b/app/routers_v2/events.py @@ -8,15 +8,12 @@ from ..db_engine import Event, model_to_dict, fn from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/events', - tags=['events'] -) +router = APIRouter(prefix="/api/v2/events", tags=["events"]) class EventModel(pydantic.BaseModel): @@ -28,76 +25,98 @@ class EventModel(pydantic.BaseModel): active: Optional[bool] = False -@router.get('') +@router.get("") async def v1_events_get( - name: Optional[str] = None, in_desc: Optional[str] = None, active: Optional[bool] = None, - csv: Optional[bool] = None): + name: Optional[str] = None, + in_desc: Optional[str] = None, + active: Optional[bool] = None, + csv: Optional[bool] = None, +): all_events = Event.select().order_by(Event.id) if name is not None: all_events = all_events.where(fn.Lower(Event.name) == name.lower()) if in_desc is not None: all_events = all_events.where( - (fn.Lower(Event.short_desc).contains(in_desc.lower())) | - (fn.Lower(Event.long_desc).contains(in_desc.lower())) + (fn.Lower(Event.short_desc).contains(in_desc.lower())) + | (fn.Lower(Event.long_desc).contains(in_desc.lower())) ) if active is not None: all_events = all_events.where(Event.active == active) if csv: - data_list = [['id', 'name', 'short_desc', 'long_desc', 'url', 'thumbnail', 'active']] + data_list = [ + ["id", "name", "short_desc", "long_desc", "url", "thumbnail", "active"] + ] for line in all_events: data_list.append( [ - line.id, line.name, line.short_desc, line.long_desc, line.url, line.thumbnail, line.active + line.id, + line.name, + line.short_desc, + line.long_desc, + line.url, + line.thumbnail, + line.active, ] ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_events.count(), 'events': []} + return_val = {"count": all_events.count(), "events": []} for x in all_events: - return_val['events'].append(model_to_dict(x)) + return_val["events"].append(model_to_dict(x)) return return_val -@router.get('/{event_id}') +@router.get("/{event_id}") async def v1_events_get_one(event_id, csv: Optional[bool] = False): try: this_event = Event.get_by_id(event_id) except Exception: - raise HTTPException(status_code=404, detail=f'No event found with id {event_id}') + raise HTTPException( + status_code=404, detail=f"No event found with id {event_id}" + ) if csv: data_list = [ - ['id', 'name', 'short_desc', 'long_desc', 'url', 'thumbnail', 'active'], - [this_event.id, this_event.name, this_event.short_desc, this_event.long_desc, this_event.url, - this_event.thumbnail, this_event.active] + ["id", "name", "short_desc", "long_desc", "url", "thumbnail", "active"], + [ + this_event.id, + this_event.name, + this_event.short_desc, + this_event.long_desc, + this_event.url, + this_event.thumbnail, + this_event.active, + ], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_event) return return_val -@router.post('') +@router.post("") async def v1_events_post(event: EventModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post events. This event has been logged.' + detail="You are not authorized to post events. This event has been logged.", ) dupe_event = Event.get_or_none(Event.name == event.name) if dupe_event: - raise HTTPException(status_code=400, detail=f'There is already an event using {event.name}') + raise HTTPException( + status_code=400, detail=f"There is already an event using {event.name}" + ) this_event = Event( name=event.name, @@ -105,7 +124,7 @@ async def v1_events_post(event: EventModel, token: str = Depends(oauth2_scheme)) long_desc=event.long_desc, url=event.url, thumbnail=event.thumbnail, - active=event.active + active=event.active, ) saved = this_event.save() @@ -115,25 +134,33 @@ async def v1_events_post(event: EventModel, token: str = Depends(oauth2_scheme)) else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that cardset' + detail="Well slap my ass and call me a teapot; I could not save that cardset", ) -@router.patch('/{event_id}') +@router.patch("/{event_id}") async def v1_events_patch( - event_id, name: Optional[str] = None, short_desc: Optional[str] = None, long_desc: Optional[str] = None, - url: Optional[str] = None, thumbnail: Optional[str] = None, active: Optional[bool] = None, - token: str = Depends(oauth2_scheme)): + event_id, + name: Optional[str] = None, + short_desc: Optional[str] = None, + long_desc: Optional[str] = None, + url: Optional[str] = None, + thumbnail: Optional[str] = None, + active: Optional[bool] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch events. This event has been logged.' + detail="You are not authorized to patch events. This event has been logged.", ) try: this_event = Event.get_by_id(event_id) except Exception: - raise HTTPException(status_code=404, detail=f'No event found with id {event_id}') + raise HTTPException( + status_code=404, detail=f"No event found with id {event_id}" + ) if name is not None: this_event.name = name @@ -154,26 +181,28 @@ async def v1_events_patch( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that event' + detail="Well slap my ass and call me a teapot; I could not save that event", ) -@router.delete('/{event_id}') +@router.delete("/{event_id}") async def v1_events_delete(event_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete events. This event has been logged.' + detail="You are not authorized to delete events. This event has been logged.", ) try: this_event = Event.get_by_id(event_id) except Exception: - raise HTTPException(status_code=404, detail=f'No event found with id {event_id}') + raise HTTPException( + status_code=404, detail=f"No event found with id {event_id}" + ) count = this_event.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Event {event_id} has been deleted') + return {"message": f"Event {event_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Event {event_id} was not deleted') + raise HTTPException(status_code=500, detail=f"Event {event_id} was not deleted") diff --git a/app/routers_v2/gamerewards.py b/app/routers_v2/gamerewards.py index c99377c..c914034 100644 --- a/app/routers_v2/gamerewards.py +++ b/app/routers_v2/gamerewards.py @@ -8,15 +8,12 @@ from ..db_engine import GameRewards, model_to_dict from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/gamerewards', - tags=['gamerewards'] -) +router = APIRouter(prefix="/api/v2/gamerewards", tags=["gamerewards"]) class GameRewardModel(pydantic.BaseModel): @@ -26,10 +23,14 @@ class GameRewardModel(pydantic.BaseModel): money: Optional[int] = None -@router.get('') +@router.get("") async def v1_gamerewards_get( - name: Optional[str] = None, pack_type_id: Optional[int] = None, player_id: Optional[int] = None, - money: Optional[int] = None, csv: Optional[bool] = None): + name: Optional[str] = None, + pack_type_id: Optional[int] = None, + player_id: Optional[int] = None, + money: Optional[int] = None, + csv: Optional[bool] = None, +): all_rewards = GameRewards.select().order_by(GameRewards.id) # if all_rewards.count() == 0: @@ -46,60 +47,72 @@ async def v1_gamerewards_get( all_rewards = all_rewards.where(GameRewards.money == money) if csv: - data_list = [['id', 'pack_type_id', 'player_id', 'money']] + data_list = [["id", "pack_type_id", "player_id", "money"]] for line in all_rewards: - data_list.append([ - line.id, line.pack_type_id if line.pack_type else None, line.player_id if line.player else None, - line.money - ]) + data_list.append( + [ + line.id, + line.pack_type_id if line.pack_type else None, + line.player_id if line.player else None, + line.money, + ] + ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_rewards.count(), 'gamerewards': []} + return_val = {"count": all_rewards.count(), "gamerewards": []} for x in all_rewards: - return_val['gamerewards'].append(model_to_dict(x)) + return_val["gamerewards"].append(model_to_dict(x)) return return_val -@router.get('/{gameaward_id}') +@router.get("/{gameaward_id}") async def v1_gamerewards_get_one(gamereward_id, csv: Optional[bool] = None): try: this_game_reward = GameRewards.get_by_id(gamereward_id) except Exception: - raise HTTPException(status_code=404, detail=f'No game reward found with id {gamereward_id}') + raise HTTPException( + status_code=404, detail=f"No game reward found with id {gamereward_id}" + ) if csv: data_list = [ - ['id', 'pack_type_id', 'player_id', 'money'], - [this_game_reward.id, this_game_reward.pack_type_id if this_game_reward.pack_type else None, - this_game_reward.player_id if this_game_reward.player else None, this_game_reward.money] + ["id", "pack_type_id", "player_id", "money"], + [ + this_game_reward.id, + this_game_reward.pack_type_id if this_game_reward.pack_type else None, + this_game_reward.player_id if this_game_reward.player else None, + this_game_reward.money, + ], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_game_reward) return return_val -@router.post('') -async def v1_gamerewards_post(game_reward: GameRewardModel, token: str = Depends(oauth2_scheme)): +@router.post("") +async def v1_gamerewards_post( + game_reward: GameRewardModel, token: str = Depends(oauth2_scheme) +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post game rewards. This event has been logged.' + detail="You are not authorized to post game rewards. This event has been logged.", ) this_award = GameRewards( name=game_reward.name, pack_type_id=game_reward.pack_type_id, player_id=game_reward.player_id, - money=game_reward.money + money=game_reward.money, ) saved = this_award.save() @@ -109,24 +122,31 @@ async def v1_gamerewards_post(game_reward: GameRewardModel, token: str = Depends else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that roster' + detail="Well slap my ass and call me a teapot; I could not save that roster", ) -@router.patch('/{game_reward_id}') +@router.patch("/{game_reward_id}") async def v1_gamerewards_patch( - game_reward_id: int, name: Optional[str] = None, pack_type_id: Optional[int] = None, - player_id: Optional[int] = None, money: Optional[int] = None, token: str = Depends(oauth2_scheme)): + game_reward_id: int, + name: Optional[str] = None, + pack_type_id: Optional[int] = None, + player_id: Optional[int] = None, + money: Optional[int] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch gamerewards. This event has been logged.' + detail="You are not authorized to patch gamerewards. This event has been logged.", ) try: this_game_reward = GameRewards.get_by_id(game_reward_id) except Exception: - raise HTTPException(status_code=404, detail=f'No game reward found with id {game_reward_id}') + raise HTTPException( + status_code=404, detail=f"No game reward found with id {game_reward_id}" + ) if name is not None: this_game_reward.name = name @@ -152,27 +172,30 @@ async def v1_gamerewards_patch( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that rarity' + detail="Well slap my ass and call me a teapot; I could not save that rarity", ) -@router.delete('/{gamereward_id}') +@router.delete("/{gamereward_id}") async def v1_gamerewards_delete(gamereward_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete awards. This event has been logged.' + detail="You are not authorized to delete awards. This event has been logged.", ) try: this_award = GameRewards.get_by_id(gamereward_id) except Exception: - raise HTTPException(status_code=404, detail=f'No award found with id {gamereward_id}') + raise HTTPException( + status_code=404, detail=f"No award found with id {gamereward_id}" + ) count = this_award.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Game Reward {gamereward_id} has been deleted') + return {"message": f"Game Reward {gamereward_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Game Reward {gamereward_id} was not deleted') - + raise HTTPException( + status_code=500, detail=f"Game Reward {gamereward_id} was not deleted" + ) diff --git a/app/routers_v2/notifications.py b/app/routers_v2/notifications.py index 7357b99..2b8bf6d 100644 --- a/app/routers_v2/notifications.py +++ b/app/routers_v2/notifications.py @@ -9,15 +9,12 @@ from ..db_engine import Notification, model_to_dict, fn from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/notifs', - tags=['notifs'] -) +router = APIRouter(prefix="/api/v2/notifs", tags=["notifs"]) class NotifModel(pydantic.BaseModel): @@ -26,19 +23,27 @@ class NotifModel(pydantic.BaseModel): desc: Optional[str] = None field_name: str message: str - about: Optional[str] = 'blank' + about: Optional[str] = "blank" ack: Optional[bool] = False -@router.get('') +@router.get("") async def get_notifs( - created_after: Optional[int] = None, title: Optional[str] = None, desc: Optional[str] = None, - field_name: Optional[str] = None, in_desc: Optional[str] = None, about: Optional[str] = None, - ack: Optional[bool] = None, csv: Optional[bool] = None): + created_after: Optional[int] = None, + title: Optional[str] = None, + desc: Optional[str] = None, + field_name: Optional[str] = None, + in_desc: Optional[str] = None, + about: Optional[str] = None, + ack: Optional[bool] = None, + csv: Optional[bool] = None, +): all_notif = Notification.select().order_by(Notification.id) if all_notif.count() == 0: - raise HTTPException(status_code=404, detail=f'There are no notifications to filter') + raise HTTPException( + status_code=404, detail=f"There are no notifications to filter" + ) if created_after is not None: # Convert milliseconds timestamp to datetime for PostgreSQL comparison @@ -51,62 +56,85 @@ async def get_notifs( if field_name is not None: all_notif = all_notif.where(Notification.field_name == field_name) if in_desc is not None: - all_notif = all_notif.where(fn.Lower(Notification.desc).contains(in_desc.lower())) + all_notif = all_notif.where( + fn.Lower(Notification.desc).contains(in_desc.lower()) + ) if about is not None: all_notif = all_notif.where(Notification.about == about) if ack is not None: all_notif = all_notif.where(Notification.ack == ack) if csv: - data_list = [['id', 'created', 'title', 'desc', 'field_name', 'message', 'about', 'ack']] + data_list = [ + ["id", "created", "title", "desc", "field_name", "message", "about", "ack"] + ] for line in all_notif: - data_list.append([ - line.id, line.created, line.title, line.desc, line.field_name, line.message, line.about, line.ack - ]) + data_list.append( + [ + line.id, + line.created, + line.title, + line.desc, + line.field_name, + line.message, + line.about, + line.ack, + ] + ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_notif.count(), 'notifs': []} + return_val = {"count": all_notif.count(), "notifs": []} for x in all_notif: - return_val['notifs'].append(model_to_dict(x)) + return_val["notifs"].append(model_to_dict(x)) return return_val -@router.get('/{notif_id}') +@router.get("/{notif_id}") async def get_one_notif(notif_id, csv: Optional[bool] = None): try: this_notif = Notification.get_by_id(notif_id) except Exception: - raise HTTPException(status_code=404, detail=f'No notification found with id {notif_id}') + raise HTTPException( + status_code=404, detail=f"No notification found with id {notif_id}" + ) if csv: data_list = [ - ['id', 'created', 'title', 'desc', 'field_name', 'message', 'about', 'ack'], - [this_notif.id, this_notif.created, this_notif.title, this_notif.desc, this_notif.field_name, - this_notif.message, this_notif.about, this_notif.ack] + ["id", "created", "title", "desc", "field_name", "message", "about", "ack"], + [ + this_notif.id, + this_notif.created, + this_notif.title, + this_notif.desc, + this_notif.field_name, + this_notif.message, + this_notif.about, + this_notif.ack, + ], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_notif) return return_val -@router.post('') +@router.post("") async def post_notif(notif: NotifModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post notifications. This event has been logged.' + detail="You are not authorized to post notifications. This event has been logged.", ) - logging.info(f'new notif: {notif}') + logging.info(f"new notif: {notif}") this_notif = Notification( created=datetime.fromtimestamp(notif.created / 1000), title=notif.title, @@ -123,25 +151,34 @@ async def post_notif(notif: NotifModel, token: str = Depends(oauth2_scheme)): else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that notification' + detail="Well slap my ass and call me a teapot; I could not save that notification", ) -@router.patch('/{notif_id}') +@router.patch("/{notif_id}") async def patch_notif( - notif_id, created: Optional[int] = None, title: Optional[str] = None, desc: Optional[str] = None, - field_name: Optional[str] = None, message: Optional[str] = None, about: Optional[str] = None, - ack: Optional[bool] = None, token: str = Depends(oauth2_scheme)): + notif_id, + created: Optional[int] = None, + title: Optional[str] = None, + desc: Optional[str] = None, + field_name: Optional[str] = None, + message: Optional[str] = None, + about: Optional[str] = None, + ack: Optional[bool] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch notifications. This event has been logged.' + detail="You are not authorized to patch notifications. This event has been logged.", ) try: this_notif = Notification.get_by_id(notif_id) except Exception: - raise HTTPException(status_code=404, detail=f'No notification found with id {notif_id}') + raise HTTPException( + status_code=404, detail=f"No notification found with id {notif_id}" + ) if title is not None: this_notif.title = title @@ -164,26 +201,30 @@ async def patch_notif( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that rarity' + detail="Well slap my ass and call me a teapot; I could not save that rarity", ) -@router.delete('/{notif_id}') +@router.delete("/{notif_id}") async def delete_notif(notif_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete notifications. This event has been logged.' + detail="You are not authorized to delete notifications. This event has been logged.", ) try: this_notif = Notification.get_by_id(notif_id) except Exception: - raise HTTPException(status_code=404, detail=f'No notification found with id {notif_id}') + raise HTTPException( + status_code=404, detail=f"No notification found with id {notif_id}" + ) count = this_notif.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Notification {notif_id} has been deleted') + return {"message": f"Notification {notif_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Notification {notif_id} was not deleted') + raise HTTPException( + status_code=500, detail=f"Notification {notif_id} was not deleted" + ) diff --git a/app/routers_v2/packs.py b/app/routers_v2/packs.py index ba4ada0..a61282b 100644 --- a/app/routers_v2/packs.py +++ b/app/routers_v2/packs.py @@ -10,15 +10,12 @@ from ..db_engine import db, Cardset, model_to_dict, Pack, Team, PackType from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/packs', - tags=['packs'] -) +router = APIRouter(prefix="/api/v2/packs", tags=["packs"]) class PackPydantic(pydantic.BaseModel): @@ -33,34 +30,47 @@ class PackModel(pydantic.BaseModel): packs: List[PackPydantic] -@router.get('') +@router.get("") async def get_packs( - team_id: Optional[int] = None, pack_type_id: Optional[int] = None, opened: Optional[bool] = None, - limit: Optional[int] = None, new_to_old: Optional[bool] = None, pack_team_id: Optional[int] = None, - pack_cardset_id: Optional[int] = None, exact_match: Optional[bool] = False, csv: Optional[bool] = None): + team_id: Optional[int] = None, + pack_type_id: Optional[int] = None, + opened: Optional[bool] = None, + limit: Optional[int] = None, + new_to_old: Optional[bool] = None, + pack_team_id: Optional[int] = None, + pack_cardset_id: Optional[int] = None, + exact_match: Optional[bool] = False, + csv: Optional[bool] = None, +): all_packs = Pack.select() if all_packs.count() == 0: - raise HTTPException(status_code=404, detail=f'There are no packs to filter') + raise HTTPException(status_code=404, detail=f"There are no packs to filter") if team_id is not None: try: this_team = Team.get_by_id(team_id) except Exception: - raise HTTPException(status_code=404, detail=f'No team found with id {team_id}') + raise HTTPException( + status_code=404, detail=f"No team found with id {team_id}" + ) all_packs = all_packs.where(Pack.team == this_team) if pack_type_id is not None: try: this_pack_type = PackType.get_by_id(pack_type_id) except Exception: - raise HTTPException(status_code=404, detail=f'No pack type found with id {pack_type_id}') + raise HTTPException( + status_code=404, detail=f"No pack type found with id {pack_type_id}" + ) all_packs = all_packs.where(Pack.pack_type == this_pack_type) if pack_team_id is not None: try: this_pack_team = Team.get_by_id(pack_team_id) except Exception: - raise HTTPException(status_code=404, detail=f'No team found with id {pack_team_id}') + raise HTTPException( + status_code=404, detail=f"No team found with id {pack_team_id}" + ) all_packs = all_packs.where(Pack.pack_team == this_pack_team) elif exact_match: all_packs = all_packs.where(Pack.pack_team == None) @@ -69,7 +79,9 @@ async def get_packs( try: this_pack_cardset = Cardset.get_by_id(pack_cardset_id) except Exception: - raise HTTPException(status_code=404, detail=f'No cardset found with id {pack_cardset_id}') + raise HTTPException( + status_code=404, detail=f"No cardset found with id {pack_cardset_id}" + ) all_packs = all_packs.where(Pack.pack_cardset == this_pack_cardset) elif exact_match: all_packs = all_packs.where(Pack.pack_cardset == None) @@ -88,55 +100,61 @@ async def get_packs( # raise HTTPException(status_code=404, detail=f'No packs found') if csv: - data_list = [['id', 'team', 'pack_type', 'open_time']] + data_list = [["id", "team", "pack_type", "open_time"]] for line in all_packs: data_list.append( [ - line.id, line.team.abbrev, line.pack_type.name, - line.open_time # Already datetime in PostgreSQL + line.id, + line.team.abbrev, + line.pack_type.name, + line.open_time, # Already datetime in PostgreSQL ] ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_packs.count(), 'packs': []} + return_val = {"count": all_packs.count(), "packs": []} for x in all_packs: - return_val['packs'].append(model_to_dict(x)) + return_val["packs"].append(model_to_dict(x)) return return_val -@router.get('/{pack_id}') +@router.get("/{pack_id}") async def get_one_pack(pack_id, csv: Optional[bool] = False): try: this_pack = Pack.get_by_id(pack_id) except Exception: - raise HTTPException(status_code=404, detail=f'No pack found with id {pack_id}') + raise HTTPException(status_code=404, detail=f"No pack found with id {pack_id}") if csv: data_list = [ - ['id', 'team', 'pack_type', 'open_time'], - [this_pack.id, this_pack.team.abbrev, this_pack.pack_type.name, - this_pack.open_time] # Already datetime in PostgreSQL + ["id", "team", "pack_type", "open_time"], + [ + this_pack.id, + this_pack.team.abbrev, + this_pack.pack_type.name, + this_pack.open_time, + ], # Already datetime in PostgreSQL ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_pack) return return_val -@router.post('') +@router.post("") async def post_pack(packs: PackModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post packs. This event has been logged.' + detail="You are not authorized to post packs. This event has been logged.", ) new_packs = [] @@ -146,23 +164,25 @@ async def post_pack(packs: PackModel, token: str = Depends(oauth2_scheme)): pack_type_id=x.pack_type_id, pack_team_id=x.pack_team_id, pack_cardset_id=x.pack_cardset_id, - open_time=datetime.fromtimestamp(x.open_time / 1000) if x.open_time else None + open_time=( + datetime.fromtimestamp(x.open_time / 1000) if x.open_time else None + ), ) new_packs.append(this_player) with db.atomic(): Pack.bulk_create(new_packs, batch_size=15) - raise HTTPException(status_code=200, detail=f'{len(new_packs)} packs have been added') + return {"message": f"{len(new_packs)} packs have been added"} -@router.post('/one') +@router.post("/one") async def post_one_pack(pack: PackPydantic, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post packs. This event has been logged.' + detail="You are not authorized to post packs. This event has been logged.", ) this_pack = Pack( @@ -170,7 +190,9 @@ async def post_one_pack(pack: PackPydantic, token: str = Depends(oauth2_scheme)) pack_type_id=pack.pack_type_id, pack_team_id=pack.pack_team_id, pack_cardset_id=pack.pack_cardset_id, - open_time=datetime.fromtimestamp(pack.open_time / 1000) if pack.open_time else None + open_time=( + datetime.fromtimestamp(pack.open_time / 1000) if pack.open_time else None + ), ) saved = this_pack.save() @@ -180,24 +202,30 @@ async def post_one_pack(pack: PackPydantic, token: str = Depends(oauth2_scheme)) else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that cardset' + detail="Well slap my ass and call me a teapot; I could not save that cardset", ) -@router.patch('/{pack_id}') +@router.patch("/{pack_id}") async def patch_pack( - pack_id, team_id: Optional[int] = None, pack_type_id: Optional[int] = None, open_time: Optional[int] = None, - pack_team_id: Optional[int] = None, pack_cardset_id: Optional[int] = None, token: str = Depends(oauth2_scheme)): + pack_id, + team_id: Optional[int] = None, + pack_type_id: Optional[int] = None, + open_time: Optional[int] = None, + pack_team_id: Optional[int] = None, + pack_cardset_id: Optional[int] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch packs. This event has been logged.' + detail="You are not authorized to patch packs. This event has been logged.", ) try: this_pack = Pack.get_by_id(pack_id) except Exception: - raise HTTPException(status_code=404, detail=f'No pack found with id {pack_id}') + raise HTTPException(status_code=404, detail=f"No pack found with id {pack_id}") if team_id is not None: this_pack.team_id = team_id @@ -225,26 +253,26 @@ async def patch_pack( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that rarity' + detail="Well slap my ass and call me a teapot; I could not save that rarity", ) -@router.delete('/{pack_id}') +@router.delete("/{pack_id}") async def delete_pack(pack_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete packs. This event has been logged.' + detail="You are not authorized to delete packs. This event has been logged.", ) try: this_pack = Pack.get_by_id(pack_id) except Exception: - raise HTTPException(status_code=404, detail=f'No packs found with id {pack_id}') + raise HTTPException(status_code=404, detail=f"No packs found with id {pack_id}") count = this_pack.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Pack {pack_id} has been deleted') + return {"message": f"Pack {pack_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Pack {pack_id} was not deleted') + raise HTTPException(status_code=500, detail=f"Pack {pack_id} was not deleted") diff --git a/app/routers_v2/packtypes.py b/app/routers_v2/packtypes.py index fb08c3a..ee388be 100644 --- a/app/routers_v2/packtypes.py +++ b/app/routers_v2/packtypes.py @@ -8,15 +8,12 @@ from ..db_engine import PackType, model_to_dict, fn from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/packtypes', - tags=['packtypes'] -) +router = APIRouter(prefix="/api/v2/packtypes", tags=["packtypes"]) class PacktypeModel(pydantic.BaseModel): @@ -27,21 +24,27 @@ class PacktypeModel(pydantic.BaseModel): available: Optional[bool] = True -@router.get('') +@router.get("") async def get_packtypes( - name: Optional[str] = None, card_count: Optional[int] = None, in_desc: Optional[str] = None, - available: Optional[bool] = None, csv: Optional[bool] = None): + name: Optional[str] = None, + card_count: Optional[int] = None, + in_desc: Optional[str] = None, + available: Optional[bool] = None, + csv: Optional[bool] = None, +): all_packtypes = PackType.select().order_by(PackType.id) if all_packtypes.count() == 0: - raise HTTPException(status_code=404, detail=f'There are no packtypes to filter') + raise HTTPException(status_code=404, detail=f"There are no packtypes to filter") if name is not None: all_packtypes = all_packtypes.where(fn.Lower(PackType.name) == name.lower()) if card_count is not None: all_packtypes = all_packtypes.where(PackType.card_count == card_count) if in_desc is not None: - all_packtypes = all_packtypes.where(fn.Lower(PackType.description).contains(in_desc.lower())) + all_packtypes = all_packtypes.where( + fn.Lower(PackType.description).contains(in_desc.lower()) + ) if available is not None: all_packtypes = all_packtypes.where(PackType.available == available) @@ -50,65 +53,70 @@ async def get_packtypes( # raise HTTPException(status_code=404, detail=f'No packtypes found') if csv: - data_list = [['id', 'name', 'card_count', 'description']] + data_list = [["id", "name", "card_count", "description"]] for line in all_packtypes: - data_list.append( - [ - line.id, line.name, line.card_count, line.description - ] - ) + data_list.append([line.id, line.name, line.card_count, line.description]) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_packtypes.count(), 'packtypes': []} + return_val = {"count": all_packtypes.count(), "packtypes": []} for x in all_packtypes: - return_val['packtypes'].append(model_to_dict(x)) + return_val["packtypes"].append(model_to_dict(x)) return return_val -@router.get('/{packtype_id}') +@router.get("/{packtype_id}") async def get_one_packtype(packtype_id, csv: Optional[bool] = False): try: this_packtype = PackType.get_by_id(packtype_id) except Exception: - raise HTTPException(status_code=404, detail=f'No packtype found with id {packtype_id}') + raise HTTPException( + status_code=404, detail=f"No packtype found with id {packtype_id}" + ) if csv: data_list = [ - ['id', 'name', 'card_count', 'description'], - [this_packtype.id, this_packtype.name, this_packtype.card_count, this_packtype.description] + ["id", "name", "card_count", "description"], + [ + this_packtype.id, + this_packtype.name, + this_packtype.card_count, + this_packtype.description, + ], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_packtype) return return_val -@router.post('') +@router.post("") async def post_packtypes(packtype: PacktypeModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post packtypes. This event has been logged.' + detail="You are not authorized to post packtypes. This event has been logged.", ) dupe_packtype = PackType.get_or_none(PackType.name == packtype.name) if dupe_packtype: - raise HTTPException(status_code=400, detail=f'There is already a packtype using {packtype.name}') + raise HTTPException( + status_code=400, detail=f"There is already a packtype using {packtype.name}" + ) this_packtype = PackType( name=packtype.name, card_count=packtype.card_count, description=packtype.description, cost=packtype.cost, - available=packtype.available + available=packtype.available, ) saved = this_packtype.save() @@ -118,24 +126,32 @@ async def post_packtypes(packtype: PacktypeModel, token: str = Depends(oauth2_sc else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that cardset' + detail="Well slap my ass and call me a teapot; I could not save that cardset", ) -@router.patch('/{packtype_id}') +@router.patch("/{packtype_id}") async def patch_packtype( - packtype_id, name: Optional[str] = None, card_count: Optional[int] = None, description: Optional[str] = None, - cost: Optional[int] = None, available: Optional[bool] = None, token: str = Depends(oauth2_scheme)): + packtype_id, + name: Optional[str] = None, + card_count: Optional[int] = None, + description: Optional[str] = None, + cost: Optional[int] = None, + available: Optional[bool] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch packtypes. This event has been logged.' + detail="You are not authorized to patch packtypes. This event has been logged.", ) try: this_packtype = PackType.get_by_id(packtype_id) except Exception: - raise HTTPException(status_code=404, detail=f'No packtype found with id {packtype_id}') + raise HTTPException( + status_code=404, detail=f"No packtype found with id {packtype_id}" + ) if name is not None: this_packtype.name = name @@ -154,26 +170,30 @@ async def patch_packtype( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that rarity' + detail="Well slap my ass and call me a teapot; I could not save that rarity", ) -@router.delete('/{packtype_id}') +@router.delete("/{packtype_id}") async def delete_packtype(packtype_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete packtypes. This event has been logged.' + detail="You are not authorized to delete packtypes. This event has been logged.", ) try: this_packtype = PackType.get_by_id(packtype_id) except Exception: - raise HTTPException(status_code=404, detail=f'No packtype found with id {packtype_id}') + raise HTTPException( + status_code=404, detail=f"No packtype found with id {packtype_id}" + ) count = this_packtype.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Packtype {packtype_id} has been deleted') + return {"message": f"Packtype {packtype_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Packtype {packtype_id} was not deleted') + raise HTTPException( + status_code=500, detail=f"Packtype {packtype_id} was not deleted" + ) diff --git a/app/routers_v2/paperdex.py b/app/routers_v2/paperdex.py index 08264e9..149edea 100644 --- a/app/routers_v2/paperdex.py +++ b/app/routers_v2/paperdex.py @@ -9,32 +9,34 @@ from ..db_engine import Paperdex, model_to_dict, Player, Cardset, Team from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/paperdex', - tags=['paperdex'] -) +router = APIRouter(prefix="/api/v2/paperdex", tags=["paperdex"]) class PaperdexModel(pydantic.BaseModel): team_id: int player_id: int - created: Optional[int] = int(datetime.timestamp(datetime.now())*1000) + created: Optional[int] = int(datetime.timestamp(datetime.now()) * 1000) -@router.get('') +@router.get("") async def get_paperdex( - team_id: Optional[int] = None, player_id: Optional[int] = None, created_after: Optional[int] = None, - cardset_id: Optional[int] = None, created_before: Optional[int] = None, flat: Optional[bool] = False, - csv: Optional[bool] = None): + team_id: Optional[int] = None, + player_id: Optional[int] = None, + created_after: Optional[int] = None, + cardset_id: Optional[int] = None, + created_before: Optional[int] = None, + flat: Optional[bool] = False, + csv: Optional[bool] = None, +): all_dex = Paperdex.select().join(Player).join(Cardset).order_by(Paperdex.id) if all_dex.count() == 0: - raise HTTPException(status_code=404, detail=f'There are no paperdex to filter') + raise HTTPException(status_code=404, detail=f"There are no paperdex to filter") if team_id is not None: all_dex = all_dex.where(Paperdex.team_id == team_id) @@ -57,56 +59,58 @@ async def get_paperdex( # raise HTTPException(status_code=404, detail=f'No paperdex found') if csv: - data_list = [['id', 'team_id', 'player_id', 'created']] + data_list = [["id", "team_id", "player_id", "created"]] for line in all_dex: data_list.append( - [ - line.id, line.team.id, line.player.player_id, line.created - ] + [line.id, line.team.id, line.player.player_id, line.created] ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_dex.count(), 'paperdex': []} + return_val = {"count": all_dex.count(), "paperdex": []} for x in all_dex: - return_val['paperdex'].append(model_to_dict(x, recurse=not flat)) + return_val["paperdex"].append(model_to_dict(x, recurse=not flat)) return return_val -@router.get('/{paperdex_id}') +@router.get("/{paperdex_id}") async def get_one_paperdex(paperdex_id, csv: Optional[bool] = False): try: this_dex = Paperdex.get_by_id(paperdex_id) except Exception: - raise HTTPException(status_code=404, detail=f'No paperdex found with id {paperdex_id}') + raise HTTPException( + status_code=404, detail=f"No paperdex found with id {paperdex_id}" + ) if csv: data_list = [ - ['id', 'team_id', 'player_id', 'created'], - [this_dex.id, this_dex.team.id, this_dex.player.id, this_dex.created] + ["id", "team_id", "player_id", "created"], + [this_dex.id, this_dex.team.id, this_dex.player.id, this_dex.created], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_dex) return return_val -@router.post('') +@router.post("") async def post_paperdex(paperdex: PaperdexModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post paperdex. This event has been logged.' + detail="You are not authorized to post paperdex. This event has been logged.", ) - dupe_dex = Paperdex.get_or_none(Paperdex.team_id == paperdex.team_id, Paperdex.player_id == paperdex.player_id) + dupe_dex = Paperdex.get_or_none( + Paperdex.team_id == paperdex.team_id, Paperdex.player_id == paperdex.player_id + ) if dupe_dex: return_val = model_to_dict(dupe_dex) return return_val @@ -114,7 +118,7 @@ async def post_paperdex(paperdex: PaperdexModel, token: str = Depends(oauth2_sch this_dex = Paperdex( team_id=paperdex.team_id, player_id=paperdex.player_id, - created=datetime.fromtimestamp(paperdex.created / 1000) + created=datetime.fromtimestamp(paperdex.created / 1000), ) saved = this_dex.save() @@ -124,24 +128,30 @@ async def post_paperdex(paperdex: PaperdexModel, token: str = Depends(oauth2_sch else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that dex' + detail="Well slap my ass and call me a teapot; I could not save that dex", ) -@router.patch('/{paperdex_id}') +@router.patch("/{paperdex_id}") async def patch_paperdex( - paperdex_id, team_id: Optional[int] = None, player_id: Optional[int] = None, created: Optional[int] = None, - token: str = Depends(oauth2_scheme)): + paperdex_id, + team_id: Optional[int] = None, + player_id: Optional[int] = None, + created: Optional[int] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch paperdex. This event has been logged.' + detail="You are not authorized to patch paperdex. This event has been logged.", ) try: this_dex = Paperdex.get_by_id(paperdex_id) except Exception: - raise HTTPException(status_code=404, detail=f'No paperdex found with id {paperdex_id}') + raise HTTPException( + status_code=404, detail=f"No paperdex found with id {paperdex_id}" + ) if team_id is not None: this_dex.team_id = team_id @@ -156,40 +166,41 @@ async def patch_paperdex( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that rarity' + detail="Well slap my ass and call me a teapot; I could not save that rarity", ) -@router.delete('/{paperdex_id}') +@router.delete("/{paperdex_id}") async def delete_paperdex(paperdex_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete rewards. This event has been logged.' + detail="You are not authorized to delete rewards. This event has been logged.", ) try: this_dex = Paperdex.get_by_id(paperdex_id) except Exception: - raise HTTPException(status_code=404, detail=f'No paperdex found with id {paperdex_id}') + raise HTTPException( + status_code=404, detail=f"No paperdex found with id {paperdex_id}" + ) count = this_dex.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Paperdex {this_dex} has been deleted') + return {"message": f"Paperdex {this_dex} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Paperdex {this_dex} was not deleted') - - -@router.post('/wipe-ai') -async def wipe_ai_paperdex(token: str = Depends(oauth2_scheme)): - if not valid_token(token): - logging.warning(f'Bad Token: {token}') raise HTTPException( - status_code=401, - detail='Unauthorized' + status_code=500, detail=f"Paperdex {this_dex} was not deleted" ) - g_teams = Team.select().where(Team.abbrev.contains('Gauntlet')) + +@router.post("/wipe-ai") +async def wipe_ai_paperdex(token: str = Depends(oauth2_scheme)): + if not valid_token(token): + logging.warning(f"Bad Token: {token}") + raise HTTPException(status_code=401, detail="Unauthorized") + + g_teams = Team.select().where(Team.abbrev.contains("Gauntlet")) count = Paperdex.delete().where(Paperdex.team << g_teams).execute() - return f'Deleted {count} records' + return f"Deleted {count} records" diff --git a/app/routers_v2/pitstats.py b/app/routers_v2/pitstats.py index 5219ca0..6eefa6c 100644 --- a/app/routers_v2/pitstats.py +++ b/app/routers_v2/pitstats.py @@ -9,15 +9,12 @@ from ..db_engine import db, PitchingStat, model_to_dict, Card, Player, Current from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/pitstats', - tags=['pitstats'] -) +router = APIRouter(prefix="/api/v2/pitstats", tags=["pitstats"]) class PitStat(pydantic.BaseModel): @@ -45,7 +42,7 @@ class PitStat(pydantic.BaseModel): bsv: Optional[int] = 0 week: int season: int - created: Optional[int] = int(datetime.timestamp(datetime.now())*1000) + created: Optional[int] = int(datetime.timestamp(datetime.now()) * 1000) game_id: int @@ -53,13 +50,22 @@ class PitchingStatModel(pydantic.BaseModel): stats: List[PitStat] -@router.get('') +@router.get("") async def get_pit_stats( - card_id: int = None, player_id: int = None, team_id: int = None, vs_team_id: int = None, week: int = None, - season: int = None, week_start: int = None, week_end: int = None, created: int = None, gs: bool = None, - csv: bool = None): + card_id: int = None, + player_id: int = None, + team_id: int = None, + vs_team_id: int = None, + week: int = None, + season: int = None, + week_start: int = None, + week_end: int = None, + created: int = None, + gs: bool = None, + csv: bool = None, +): all_stats = PitchingStat.select().join(Card).join(Player).order_by(PitchingStat.id) - logging.debug(f'pit query:\n\n{all_stats}') + logging.debug(f"pit query:\n\n{all_stats}") if season is not None: all_stats = all_stats.where(PitchingStat.season == season) @@ -93,38 +99,92 @@ async def get_pit_stats( # raise HTTPException(status_code=404, detail=f'No pitching stats found') if csv: - data_list = [['id', 'card_id', 'player_id', 'cardset', 'team', 'vs_team', 'ip', 'hit', 'run', 'erun', 'so', 'bb', 'hbp', - 'wp', 'balk', 'hr', 'ir', 'irs', 'gs', 'win', 'loss', 'hold', 'sv', 'bsv', 'week', 'season', - 'created', 'game_id', 'roster_num']] + data_list = [ + [ + "id", + "card_id", + "player_id", + "cardset", + "team", + "vs_team", + "ip", + "hit", + "run", + "erun", + "so", + "bb", + "hbp", + "wp", + "balk", + "hr", + "ir", + "irs", + "gs", + "win", + "loss", + "hold", + "sv", + "bsv", + "week", + "season", + "created", + "game_id", + "roster_num", + ] + ] for line in all_stats: data_list.append( [ - line.id, line.card.id, line.card.player.player_id, line.card.player.cardset.name, line.team.abbrev, - line.vs_team.abbrev, line.ip, line.hit, - line.run, line.erun, line.so, line.bb, line.hbp, line.wp, line.balk, line.hr, line.ir, line.irs, - line.gs, line.win, line.loss, line.hold, line.sv, line.bsv, line.week, line.season, line.created, - line.game_id, line.roster_num + line.id, + line.card.id, + line.card.player.player_id, + line.card.player.cardset.name, + line.team.abbrev, + line.vs_team.abbrev, + line.ip, + line.hit, + line.run, + line.erun, + line.so, + line.bb, + line.hbp, + line.wp, + line.balk, + line.hr, + line.ir, + line.irs, + line.gs, + line.win, + line.loss, + line.hold, + line.sv, + line.bsv, + line.week, + line.season, + line.created, + line.game_id, + line.roster_num, ] ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_stats.count(), 'stats': []} + return_val = {"count": all_stats.count(), "stats": []} for x in all_stats: - return_val['stats'].append(model_to_dict(x, recurse=False)) + return_val["stats"].append(model_to_dict(x, recurse=False)) return return_val -@router.post('') +@router.post("") async def post_pitstat(stats: PitchingStatModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post stats. This event has been logged.' + detail="You are not authorized to post stats. This event has been logged.", ) new_stats = [] @@ -154,33 +214,37 @@ async def post_pitstat(stats: PitchingStatModel, token: str = Depends(oauth2_sch bsv=x.bsv, week=x.week, season=x.season, - created=datetime.fromtimestamp(x.created / 1000) if x.created else datetime.now(), - game_id=x.game_id + created=( + datetime.fromtimestamp(x.created / 1000) + if x.created + else datetime.now() + ), + game_id=x.game_id, ) new_stats.append(this_stat) with db.atomic(): PitchingStat.bulk_create(new_stats, batch_size=15) - raise HTTPException(status_code=200, detail=f'{len(new_stats)} pitching lines have been added') + return {"message": f"{len(new_stats)} pitching lines have been added"} -@router.delete('/{stat_id}') +@router.delete("/{stat_id}") async def delete_pitstat(stat_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete stats. This event has been logged.' + detail="You are not authorized to delete stats. This event has been logged.", ) try: this_stat = PitchingStat.get_by_id(stat_id) except Exception: - raise HTTPException(status_code=404, detail=f'No stat found with id {stat_id}') + raise HTTPException(status_code=404, detail=f"No stat found with id {stat_id}") count = this_stat.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Stat {stat_id} has been deleted') + return {"message": f"Stat {stat_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Stat {stat_id} was not deleted') + raise HTTPException(status_code=500, detail=f"Stat {stat_id} was not deleted") diff --git a/app/routers_v2/rarity.py b/app/routers_v2/rarity.py index e37156e..7e53b69 100644 --- a/app/routers_v2/rarity.py +++ b/app/routers_v2/rarity.py @@ -8,15 +8,12 @@ from ..db_engine import Rarity, model_to_dict, fn from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/rarities', - tags=['rarities'] -) +router = APIRouter(prefix="/api/v2/rarities", tags=["rarities"]) class RarityModel(pydantic.BaseModel): @@ -25,13 +22,18 @@ class RarityModel(pydantic.BaseModel): 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): +@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') + 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) @@ -43,69 +45,61 @@ async def get_rarities(value: Optional[int] = None, name: Optional[str] = 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') + raise HTTPException(status_code=404, detail=f"No rarities found") if csv: - data_list = [['id', 'value', 'name']] + data_list = [["id", "value", "name"]] for line in all_rarities: - data_list.append( - [ - line.id, line.value, line.name - ] - ) + 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') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_rarities.count(), 'rarities': []} + return_val = {"count": all_rarities.count(), "rarities": []} for x in all_rarities: - return_val['rarities'].append(model_to_dict(x)) + return_val["rarities"].append(model_to_dict(x)) return return_val -@router.get('/{rarity_id}') +@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 Exception: - raise HTTPException(status_code=404, detail=f'No rarity found with id {rarity_id}') + raise HTTPException( + status_code=404, detail=f"No rarity found with id {rarity_id}" + ) if csv: - data_list = [['id', 'value', 'name']] + data_list = [["id", "value", "name"]] for line in this_rarity: - data_list.append( - [ - line.id, line.value, line.name - ] - ) + 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') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_rarity) return return_val -@router.post('') +@router.post("") async def post_rarity(rarity: RarityModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post rarities. This event has been logged.' + 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}') + 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 - ) + this_rarity = Rarity(value=rarity.value, name=rarity.name, color=rarity.color) saved = this_rarity.save() if saved == 1: @@ -114,24 +108,30 @@ async def post_rarity(rarity: RarityModel, token: str = Depends(oauth2_scheme)): else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that rarity' + detail="Well slap my ass and call me a teapot; I could not save that rarity", ) -@router.patch('/{rarity_id}') +@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)): + 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(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch rarities. This event has been logged.' + detail="You are not authorized to patch rarities. This event has been logged.", ) try: this_rarity = Rarity.get_by_id(rarity_id) except Exception: - raise HTTPException(status_code=404, detail=f'No rarity found with id {rarity_id}') + raise HTTPException( + status_code=404, detail=f"No rarity found with id {rarity_id}" + ) if value is not None: this_rarity.value = value @@ -146,26 +146,30 @@ async def patch_rarity( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that rarity' + detail="Well slap my ass and call me a teapot; I could not save that rarity", ) -@router.delete('/{rarity_id}') +@router.delete("/{rarity_id}") async def v1_rarities_delete(rarity_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete rarities. This event has been logged.' + detail="You are not authorized to delete rarities. This event has been logged.", ) try: this_rarity = Rarity.get_by_id(rarity_id) except Exception: - raise HTTPException(status_code=404, detail=f'No rarity found with id {rarity_id}') + 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') + return {"message": f"Rarity {rarity_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Rarity {rarity_id} was not deleted') + raise HTTPException( + status_code=500, detail=f"Rarity {rarity_id} was not deleted" + ) diff --git a/app/routers_v2/results.py b/app/routers_v2/results.py index c706a41..4a857b6 100644 --- a/app/routers_v2/results.py +++ b/app/routers_v2/results.py @@ -8,15 +8,12 @@ from ..db_engine import Result, model_to_dict, Team, DataError from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/results', - tags=['results'] -) +router = APIRouter(prefix="/api/v2/results", tags=["results"]) class ResultModel(pydantic.BaseModel): @@ -36,15 +33,28 @@ class ResultModel(pydantic.BaseModel): game_type: str -@router.get('') +@router.get("") async def get_results( - away_team_id: Optional[int] = None, home_team_id: Optional[int] = None, team_one_id: Optional[int] = None, - team_two_id: Optional[int] = None, away_score_min: Optional[int] = None, away_score_max: Optional[int] = None, - home_score_min: Optional[int] = None, home_score_max: Optional[int] = None, bothscore_min: Optional[int] = None, - bothscore_max: Optional[int] = None, season: Optional[int] = None, week: Optional[int] = None, - week_start: Optional[int] = None, week_end: Optional[int] = None, ranked: Optional[bool] = None, - short_game: Optional[bool] = None, game_type: Optional[str] = None, vs_ai: Optional[bool] = None, - csv: Optional[bool] = None): + away_team_id: Optional[int] = None, + home_team_id: Optional[int] = None, + team_one_id: Optional[int] = None, + team_two_id: Optional[int] = None, + away_score_min: Optional[int] = None, + away_score_max: Optional[int] = None, + home_score_min: Optional[int] = None, + home_score_max: Optional[int] = None, + bothscore_min: Optional[int] = None, + bothscore_max: Optional[int] = None, + season: Optional[int] = None, + week: Optional[int] = None, + week_start: Optional[int] = None, + week_end: Optional[int] = None, + ranked: Optional[bool] = None, + short_game: Optional[bool] = None, + game_type: Optional[str] = None, + vs_ai: Optional[bool] = None, + csv: Optional[bool] = None, +): all_results = Result.select() # if all_results.count() == 0: @@ -56,28 +66,40 @@ async def get_results( this_team = Team.get_by_id(away_team_id) all_results = all_results.where(Result.away_team == this_team) except Exception: - raise HTTPException(status_code=404, detail=f'No team found with id {away_team_id}') + raise HTTPException( + status_code=404, detail=f"No team found with id {away_team_id}" + ) if home_team_id is not None: try: this_team = Team.get_by_id(home_team_id) all_results = all_results.where(Result.home_team == this_team) except Exception: - raise HTTPException(status_code=404, detail=f'No team found with id {home_team_id}') + raise HTTPException( + status_code=404, detail=f"No team found with id {home_team_id}" + ) if team_one_id is not None: try: this_team = Team.get_by_id(team_one_id) - all_results = all_results.where((Result.home_team == this_team) | (Result.away_team == this_team)) + all_results = all_results.where( + (Result.home_team == this_team) | (Result.away_team == this_team) + ) except Exception: - raise HTTPException(status_code=404, detail=f'No team found with id {team_one_id}') + raise HTTPException( + status_code=404, detail=f"No team found with id {team_one_id}" + ) if team_two_id is not None: try: this_team = Team.get_by_id(team_two_id) - all_results = all_results.where((Result.home_team == this_team) | (Result.away_team == this_team)) + all_results = all_results.where( + (Result.home_team == this_team) | (Result.away_team == this_team) + ) except Exception: - raise HTTPException(status_code=404, detail=f'No team found with id {team_two_id}') + raise HTTPException( + status_code=404, detail=f"No team found with id {team_two_id}" + ) if away_score_min is not None: all_results = all_results.where(Result.away_score >= away_score_min) @@ -92,10 +114,14 @@ async def get_results( all_results = all_results.where(Result.home_score <= home_score_max) if bothscore_min is not None: - all_results = all_results.where((Result.home_score >= bothscore_min) & (Result.away_score >= bothscore_min)) + all_results = all_results.where( + (Result.home_score >= bothscore_min) & (Result.away_score >= bothscore_min) + ) if bothscore_max is not None: - all_results = all_results.where((Result.home_score <= bothscore_max) & (Result.away_score <= bothscore_max)) + all_results = all_results.where( + (Result.home_score <= bothscore_max) & (Result.away_score <= bothscore_max) + ) if season is not None: all_results = all_results.where(Result.season == season) @@ -139,60 +165,115 @@ async def get_results( # logging.info(f'Result Query:\n\n{all_results}') if csv: - data_list = [['id', 'away_abbrev', 'home_abbrev', 'away_score', 'home_score', 'away_tv', 'home_tv', - 'game_type', 'season', 'week', 'short_game', 'ranked']] + data_list = [ + [ + "id", + "away_abbrev", + "home_abbrev", + "away_score", + "home_score", + "away_tv", + "home_tv", + "game_type", + "season", + "week", + "short_game", + "ranked", + ] + ] for line in all_results: - data_list.append([ - line.id, line.away_team.abbrev, line.home_team.abbrev, line.away_score, line.home_score, - line.away_team_value, line.home_team_value, line.game_type if line.game_type else 'minor-league', - line.season, line.week, line.short_game, line.ranked - ]) + data_list.append( + [ + line.id, + line.away_team.abbrev, + line.home_team.abbrev, + line.away_score, + line.home_score, + line.away_team_value, + line.home_team_value, + line.game_type if line.game_type else "minor-league", + line.season, + line.week, + line.short_game, + line.ranked, + ] + ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_results.count(), 'results': []} + return_val = {"count": all_results.count(), "results": []} for x in all_results: - return_val['results'].append(model_to_dict(x)) + return_val["results"].append(model_to_dict(x)) return return_val -@router.get('/{result_id}') +@router.get("/{result_id}") async def get_one_results(result_id, csv: Optional[bool] = None): try: this_result = Result.get_by_id(result_id) except Exception: - raise HTTPException(status_code=404, detail=f'No result found with id {result_id}') + raise HTTPException( + status_code=404, detail=f"No result found with id {result_id}" + ) if csv: data_list = [ - ['id', 'away_abbrev', 'home_abbrev', 'away_score', 'home_score', 'away_tv', 'home_tv', 'game_type', - 'season', 'week', 'game_type'], - [this_result.id, this_result.away_team.abbrev, this_result.away_team.abbrev, this_result.away_score, - this_result.home_score, this_result.away_team_value, this_result.home_team_value, - this_result.game_type if this_result.game_type else 'minor-league', - this_result.season, this_result.week, this_result.game_type] + [ + "id", + "away_abbrev", + "home_abbrev", + "away_score", + "home_score", + "away_tv", + "home_tv", + "game_type", + "season", + "week", + "game_type", + ], + [ + this_result.id, + this_result.away_team.abbrev, + this_result.away_team.abbrev, + this_result.away_score, + this_result.home_score, + this_result.away_team_value, + this_result.home_team_value, + this_result.game_type if this_result.game_type else "minor-league", + this_result.season, + this_result.week, + this_result.game_type, + ], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_result) return return_val -@router.get('/team/{team_id}') +@router.get("/team/{team_id}") async def get_team_results( - team_id: int, season: Optional[int] = None, week: Optional[int] = None, csv: Optional[bool] = False): - all_results = Result.select().where((Result.away_team_id == team_id) | (Result.home_team_id == team_id)).order_by(Result.id) + team_id: int, + season: Optional[int] = None, + week: Optional[int] = None, + csv: Optional[bool] = False, +): + all_results = ( + Result.select() + .where((Result.away_team_id == team_id) | (Result.home_team_id == team_id)) + .order_by(Result.id) + ) try: this_team = Team.get_by_id(team_id) except Exception as e: - logging.error(f'Unknown team id {team_id} trying to pull team results') - raise HTTPException(404, f'Team id {team_id} not found') + logging.error(f"Unknown team id {team_id} trying to pull team results") + raise HTTPException(404, f"Team id {team_id} not found") if season is not None: all_results = all_results.where(Result.season == season) @@ -229,31 +310,38 @@ async def get_team_results( if csv: data_list = [ - ['team_id', 'ranked_wins', 'ranked_losses', 'casual_wins', 'casual_losses', 'team_ranking'], - [team_id, r_wins, r_loss, c_wins, c_loss, this_team.ranking] + [ + "team_id", + "ranked_wins", + "ranked_losses", + "casual_wins", + "casual_losses", + "team_ranking", + ], + [team_id, r_wins, r_loss, c_wins, c_loss, this_team.ranking], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = { - 'team': model_to_dict(this_team), - 'ranked_wins': r_wins, - 'ranked_losses': r_loss, - 'casual_wins': c_wins, - 'casual_losses': c_loss, + "team": model_to_dict(this_team), + "ranked_wins": r_wins, + "ranked_losses": r_loss, + "casual_wins": c_wins, + "casual_losses": c_loss, } return return_val -@router.post('') +@router.post("") async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post results. This event has been logged.' + detail="You are not authorized to post results. This event has been logged.", ) this_result = Result(**result.__dict__) @@ -261,24 +349,28 @@ async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)): if result.ranked: if not result.away_team_ranking: - error = f'Ranked game did not include away team ({result.away_team_id}) ranking.' + error = f"Ranked game did not include away team ({result.away_team_id}) ranking." logging.error(error) raise DataError(error) if not result.home_team_ranking: - error = f'Ranked game did not include home team ({result.home_team_id}) ranking.' + error = f"Ranked game did not include home team ({result.home_team_id}) ranking." logging.error(error) raise DataError(error) k_value = 20 if result.short_game else 60 ratio = (result.home_team_ranking - result.away_team_ranking) / 400 - exp_score = 1 / (1 + (10 ** ratio)) + exp_score = 1 / (1 + (10**ratio)) away_win = True if result.away_score > result.home_score else False total_delta = k_value * exp_score - high_delta = total_delta * exp_score if exp_score > .5 else total_delta * (1 - exp_score) + high_delta = ( + total_delta * exp_score + if exp_score > 0.5 + else total_delta * (1 - exp_score) + ) low_delta = total_delta - high_delta # exp_score > .5 means away team is favorite - if exp_score > .5 and away_win: + if exp_score > 0.5 and away_win: final_delta = low_delta away_delta = low_delta * 3 home_delta = -low_delta @@ -286,7 +378,7 @@ async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)): final_delta = high_delta away_delta = high_delta * 3 home_delta = -high_delta - elif exp_score <= .5 and not away_win: + elif exp_score <= 0.5 and not away_win: final_delta = low_delta away_delta = -low_delta home_delta = low_delta * 3 @@ -299,18 +391,20 @@ async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)): away_delta = 0 home_delta = 0 - logging.debug(f'/results ranking deltas\n\nk_value: {k_value} / ratio: {ratio} / ' - f'exp_score: {exp_score} / away_win: {away_win} / total_delta: {total_delta} / ' - f'high_delta: {high_delta} / low_delta: {low_delta} / final_delta: {final_delta} / ') + logging.debug( + f"/results ranking deltas\n\nk_value: {k_value} / ratio: {ratio} / " + f"exp_score: {exp_score} / away_win: {away_win} / total_delta: {total_delta} / " + f"high_delta: {high_delta} / low_delta: {low_delta} / final_delta: {final_delta} / " + ) away_team = Team.get_by_id(result.away_team_id) away_team.ranking += away_delta away_team.save() - logging.info(f'Just updated {away_team.abbrev} ranking to {away_team.ranking}') + logging.info(f"Just updated {away_team.abbrev} ranking to {away_team.ranking}") home_team = Team.get_by_id(result.home_team_id) home_team.ranking += home_delta home_team.save() - logging.info(f'Just updated {home_team.abbrev} ranking to {home_team.ranking}') + logging.info(f"Just updated {home_team.abbrev} ranking to {home_team.ranking}") if saved == 1: return_val = model_to_dict(this_result) @@ -318,27 +412,38 @@ async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)): else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that roster' + detail="Well slap my ass and call me a teapot; I could not save that roster", ) -@router.patch('/{result_id}') +@router.patch("/{result_id}") async def patch_result( - result_id, away_team_id: Optional[int] = None, home_team_id: Optional[int] = None, - away_score: Optional[int] = None, home_score: Optional[int] = None, away_team_value: Optional[int] = None, - home_team_value: Optional[int] = None, scorecard: Optional[str] = None, week: Optional[int] = None, - season: Optional[int] = None, short_game: Optional[bool] = None, game_type: Optional[str] = None, - token: str = Depends(oauth2_scheme)): + result_id, + away_team_id: Optional[int] = None, + home_team_id: Optional[int] = None, + away_score: Optional[int] = None, + home_score: Optional[int] = None, + away_team_value: Optional[int] = None, + home_team_value: Optional[int] = None, + scorecard: Optional[str] = None, + week: Optional[int] = None, + season: Optional[int] = None, + short_game: Optional[bool] = None, + game_type: Optional[str] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch results. This event has been logged.' + detail="You are not authorized to patch results. This event has been logged.", ) try: this_result = Result.get_by_id(result_id) except Exception: - raise HTTPException(status_code=404, detail=f'No result found with id {result_id}') + raise HTTPException( + status_code=404, detail=f"No result found with id {result_id}" + ) if away_team_id is not None: this_result.away_team_id = away_team_id @@ -382,27 +487,30 @@ async def patch_result( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that event' + detail="Well slap my ass and call me a teapot; I could not save that event", ) -@router.delete('/{result_id}') +@router.delete("/{result_id}") async def delete_result(result_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post results. This event has been logged.' + detail="You are not authorized to post results. This event has been logged.", ) try: this_result = Result.get_by_id(result_id) except Exception: - raise HTTPException(status_code=404, detail=f'No result found with id {result_id}') + raise HTTPException( + status_code=404, detail=f"No result found with id {result_id}" + ) count = this_result.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Result {result_id} has been deleted') + return {"message": f"Result {result_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Result {result_id} was not deleted') - + raise HTTPException( + status_code=500, detail=f"Result {result_id} was not deleted" + ) diff --git a/app/routers_v2/rewards.py b/app/routers_v2/rewards.py index 86f46ff..3405e4f 100644 --- a/app/routers_v2/rewards.py +++ b/app/routers_v2/rewards.py @@ -9,15 +9,12 @@ from ..db_engine import Reward, model_to_dict, fn from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( - filename=LOG_DATA['filename'], - format=LOG_DATA['format'], - level=LOG_DATA['log_level'] + filename=LOG_DATA["filename"], + format=LOG_DATA["format"], + level=LOG_DATA["log_level"], ) -router = APIRouter( - prefix='/api/v2/rewards', - tags=['rewards'] -) +router = APIRouter(prefix="/api/v2/rewards", tags=["rewards"]) class RewardModel(pydantic.BaseModel): @@ -25,18 +22,24 @@ class RewardModel(pydantic.BaseModel): season: int week: int team_id: int - created: Optional[int] = int(datetime.timestamp(datetime.now())*1000) + created: Optional[int] = int(datetime.timestamp(datetime.now()) * 1000) -@router.get('') +@router.get("") async def get_rewards( - name: Optional[str] = None, in_name: Optional[str] = None, team_id: Optional[int] = None, - season: Optional[int] = None, week: Optional[int] = None, created_after: Optional[int] = None, - flat: Optional[bool] = False, csv: Optional[bool] = None): + name: Optional[str] = None, + in_name: Optional[str] = None, + team_id: Optional[int] = None, + season: Optional[int] = None, + week: Optional[int] = None, + created_after: Optional[int] = None, + flat: Optional[bool] = False, + csv: Optional[bool] = None, +): all_rewards = Reward.select().order_by(Reward.id) if all_rewards.count() == 0: - raise HTTPException(status_code=404, detail=f'There are no rewards to filter') + raise HTTPException(status_code=404, detail=f"There are no rewards to filter") if name is not None: all_rewards = all_rewards.where(fn.Lower(Reward.name) == name.lower()) @@ -54,62 +57,68 @@ async def get_rewards( all_rewards = all_rewards.where(Reward.week == week) if all_rewards.count() == 0: - raise HTTPException(status_code=404, detail=f'No rewards found') + raise HTTPException(status_code=404, detail=f"No rewards found") if csv: - data_list = [['id', 'name', 'team', 'daily', 'created']] + data_list = [["id", "name", "team", "daily", "created"]] for line in all_rewards: data_list.append( - [ - line.id, line.name, line.team.id, line.daily, line.created - ] + [line.id, line.name, line.team.id, line.daily, line.created] ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: - return_val = {'count': all_rewards.count(), 'rewards': []} + return_val = {"count": all_rewards.count(), "rewards": []} for x in all_rewards: - return_val['rewards'].append(model_to_dict(x, recurse=not flat)) + return_val["rewards"].append(model_to_dict(x, recurse=not flat)) return return_val -@router.get('/{reward_id}') +@router.get("/{reward_id}") async def get_one_reward(reward_id, csv: Optional[bool] = False): try: this_reward = Reward.get_by_id(reward_id) except Exception: - raise HTTPException(status_code=404, detail=f'No reward found with id {reward_id}') + raise HTTPException( + status_code=404, detail=f"No reward found with id {reward_id}" + ) if csv: data_list = [ - ['id', 'name', 'card_count', 'description'], - [this_reward.id, this_reward.name, this_reward.team.id, this_reward.daily, this_reward.created] + ["id", "name", "card_count", "description"], + [ + this_reward.id, + this_reward.name, + this_reward.team.id, + this_reward.daily, + this_reward.created, + ], ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - return Response(content=return_val, media_type='text/csv') + return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_reward) return return_val -@router.post('') +@router.post("") async def post_rewards(reward: RewardModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to post rewards. This event has been logged.' + detail="You are not authorized to post rewards. This event has been logged.", ) reward_data = reward.dict() # Convert milliseconds timestamp to datetime for PostgreSQL - if reward_data.get('created'): - reward_data['created'] = datetime.fromtimestamp(reward_data['created'] / 1000) + if reward_data.get("created"): + reward_data["created"] = datetime.fromtimestamp(reward_data["created"] / 1000) this_reward = Reward(**reward_data) saved = this_reward.save() @@ -119,24 +128,30 @@ async def post_rewards(reward: RewardModel, token: str = Depends(oauth2_scheme)) else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that cardset' + detail="Well slap my ass and call me a teapot; I could not save that cardset", ) -@router.patch('/{reward_id}') +@router.patch("/{reward_id}") async def patch_reward( - reward_id, name: Optional[str] = None, team_id: Optional[int] = None, created: Optional[int] = None, - token: str = Depends(oauth2_scheme)): + reward_id, + name: Optional[str] = None, + team_id: Optional[int] = None, + created: Optional[int] = None, + token: str = Depends(oauth2_scheme), +): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to patch rewards. This event has been logged.' + detail="You are not authorized to patch rewards. This event has been logged.", ) try: this_reward = Reward.get_by_id(reward_id) except Exception: - raise HTTPException(status_code=404, detail=f'No reward found with id {reward_id}') + raise HTTPException( + status_code=404, detail=f"No reward found with id {reward_id}" + ) if name is not None: this_reward.name = name @@ -152,28 +167,30 @@ async def patch_reward( else: raise HTTPException( status_code=418, - detail='Well slap my ass and call me a teapot; I could not save that rarity' + detail="Well slap my ass and call me a teapot; I could not save that rarity", ) -@router.delete('/{reward_id}') +@router.delete("/{reward_id}") async def delete_reward(reward_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): - logging.warning(f'Bad Token: {token}') + logging.warning(f"Bad Token: {token}") raise HTTPException( status_code=401, - detail='You are not authorized to delete rewards. This event has been logged.' + detail="You are not authorized to delete rewards. This event has been logged.", ) try: this_reward = Reward.get_by_id(reward_id) except Exception: - raise HTTPException(status_code=404, detail=f'No reward found with id {reward_id}') + raise HTTPException( + status_code=404, detail=f"No reward found with id {reward_id}" + ) count = this_reward.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f'Reward {reward_id} has been deleted') + return {"message": f"Reward {reward_id} has been deleted"} else: - raise HTTPException(status_code=500, detail=f'Reward {reward_id} was not deleted') - - + raise HTTPException( + status_code=500, detail=f"Reward {reward_id} was not deleted" + ) diff --git a/app/routers_v2/teams.py b/app/routers_v2/teams.py index c6b27ca..dca7936 100644 --- a/app/routers_v2/teams.py +++ b/app/routers_v2/teams.py @@ -282,7 +282,6 @@ def get_scouting_dfs(allowed_players, position: str): ) ) - def get_total_ops(df_data): ops_vl = df_data["obp_vl"] + df_data["slg_vl"] ops_vr = df_data["obp_vr"] + df_data["slg_vr"] @@ -1506,6 +1505,6 @@ async def delete_team(team_id, token: str = Depends(oauth2_scheme)): count = this_team.delete_instance() if count == 1: - raise HTTPException(status_code=200, detail=f"Team {team_id} has been deleted") + return {"message": f"Team {team_id} has been deleted"} else: raise HTTPException(status_code=500, detail=f"Team {team_id} was not deleted")