From 8c6a99253b118258b0c5d7a523dbef5274871445 Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Mon, 2 Mar 2026 23:37:24 -0600 Subject: [PATCH] fix: replace 467 manual db.close() calls with middleware (#30) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add db_session_middleware to main.py that opens the connection at the start of each request and closes it in a try/finally block, ensuring connections are always returned even on uncaught exceptions. Remove all individual db.close() calls from 30 router files in app/routers_v2/ — the middleware now handles all code paths. Co-Authored-By: Claude Sonnet 4.6 --- app/main.py | 57 +++++++++++++++++++++++---- app/routers_v2/admin.py | 2 - app/routers_v2/awards.py | 12 ------ app/routers_v2/batstats.py | 9 ----- app/routers_v2/battingcardratings.py | 17 -------- app/routers_v2/battingcards.py | 14 ------- app/routers_v2/cardpositions.py | 8 ---- app/routers_v2/cards.py | 23 ----------- app/routers_v2/cardsets.py | 18 --------- app/routers_v2/current.py | 14 ------- app/routers_v2/decisions.py | 11 ------ app/routers_v2/events.py | 16 -------- app/routers_v2/gamerewards.py | 14 ------- app/routers_v2/gauntletrewards.py | 9 ----- app/routers_v2/gauntletruns.py | 10 ----- app/routers_v2/mlbplayers.py | 21 ---------- app/routers_v2/notifications.py | 15 ------- app/routers_v2/packs.py | 20 ---------- app/routers_v2/packtypes.py | 15 ------- app/routers_v2/paperdex.py | 16 -------- app/routers_v2/pitchingcardratings.py | 16 -------- app/routers_v2/pitchingcards.py | 14 ------- app/routers_v2/pitstats.py | 7 ---- app/routers_v2/players.py | 29 -------------- app/routers_v2/rarity.py | 16 -------- app/routers_v2/results.py | 23 ----------- app/routers_v2/rewards.py | 15 ------- app/routers_v2/scouting.py | 3 -- app/routers_v2/stratgame.py | 10 ----- app/routers_v2/stratplays.py | 16 -------- app/routers_v2/teams.py | 54 ------------------------- 31 files changed, 49 insertions(+), 475 deletions(-) diff --git a/app/main.py b/app/main.py index 057e321..4f68ff8 100644 --- a/app/main.py +++ b/app/main.py @@ -5,16 +5,44 @@ from fastapi.openapi.utils import get_openapi # from fastapi.staticfiles import StaticFiles # from fastapi.templating import Jinja2Templates +from .db_engine import db from .routers_v2 import ( - current, awards, teams, rarity, cardsets, players, packtypes, packs, cards, events, results, rewards, decisions, - batstats, pitstats, notifications, paperdex, gamerewards, gauntletrewards, gauntletruns, battingcards, - battingcardratings, pitchingcards, pitchingcardratings, cardpositions, scouting, mlbplayers, stratgame, stratplays) + current, + awards, + teams, + rarity, + cardsets, + players, + packtypes, + packs, + cards, + events, + results, + rewards, + decisions, + batstats, + pitstats, + notifications, + paperdex, + gamerewards, + gauntletrewards, + gauntletruns, + battingcards, + battingcardratings, + pitchingcards, + pitchingcardratings, + cardpositions, + scouting, + mlbplayers, + stratgame, + stratplays, +) app = FastAPI( # root_path='/api', - responses={404: {'description': 'Not found'}}, - docs_url='/api/docs', - redoc_url='/api/redoc' + responses={404: {"description": "Not found"}}, + docs_url="/api/docs", + redoc_url="/api/redoc", ) # app.mount("/static", StaticFiles(directory="storage/static"), name="static") @@ -51,12 +79,25 @@ app.include_router(stratplays.router) app.include_router(decisions.router) +@app.middleware("http") +async def db_session_middleware(request: Request, call_next): + try: + db.connect(reuse_if_open=True) + response = await call_next(request) + return response + finally: + if not db.is_closed(): + db.close() + + @app.get("/api/docs", include_in_schema=False) async def get_docs(req: Request): print(req.scope) - return get_swagger_ui_html(openapi_url=req.scope.get('root_path')+'/openapi.json', title='Swagger') + return get_swagger_ui_html( + openapi_url=req.scope.get("root_path") + "/openapi.json", title="Swagger" + ) @app.get("/api/openapi.json", include_in_schema=False) async def openapi(): - return get_openapi(title='Paper Dynasty API', version=f'0.1.1', routes=app.routes) + return get_openapi(title="Paper Dynasty API", version=f"0.1.1", routes=app.routes) diff --git a/app/routers_v2/admin.py b/app/routers_v2/admin.py index 89eba55..350897b 100644 --- a/app/routers_v2/admin.py +++ b/app/routers_v2/admin.py @@ -20,7 +20,6 @@ router = APIRouter( async def stl_cardinals_fix(token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post. This event has been logged.' @@ -29,7 +28,6 @@ async def stl_cardinals_fix(token: str = Depends(oauth2_scheme)): p_query = Player.update(mlbclub='St Louis Cardinals', franchise='St Louis Cardinals').where( Player.mlbclub == 'St. Louis Cardinals' ).execute() - db.close() return {'detail': f'Removed the period from St Louis'} diff --git a/app/routers_v2/awards.py b/app/routers_v2/awards.py index 27c170c..e871c17 100644 --- a/app/routers_v2/awards.py +++ b/app/routers_v2/awards.py @@ -41,7 +41,6 @@ async def get_awards( all_awards = Award.select().order_by(Award.id) if all_awards.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f'There are no awards to filter') if name is not None: @@ -65,7 +64,6 @@ async def get_awards( ]) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -73,7 +71,6 @@ async def get_awards( for x in all_awards: return_val['awards'].append(model_to_dict(x)) - db.close() return return_val @@ -82,7 +79,6 @@ async def get_one_award(award_id, csv: Optional[bool] = None): try: this_award = Award.get_by_id(award_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No award found with id {award_id}') if csv: @@ -93,12 +89,10 @@ async def get_one_award(award_id, csv: Optional[bool] = None): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_award) - db.close() return return_val @@ -106,7 +100,6 @@ async def get_one_award(award_id, csv: Optional[bool] = None): async def post_awards(award: AwardModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post awards. This event has been logged.' @@ -124,10 +117,8 @@ async def post_awards(award: AwardModel, token: str = Depends(oauth2_scheme)): saved = this_award.save() if saved == 1: return_val = model_to_dict(this_award) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail='Well slap my ass and call me a teapot; I could not save that roster' @@ -138,7 +129,6 @@ async def post_awards(award: AwardModel, token: str = Depends(oauth2_scheme)): async def delete_award(award_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete awards. This event has been logged.' @@ -146,11 +136,9 @@ async def delete_award(award_id, token: str = Depends(oauth2_scheme)): try: this_award = Award.get_by_id(award_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No award found with id {award_id}') count = this_award.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Award {award_id} has been deleted') diff --git a/app/routers_v2/batstats.py b/app/routers_v2/batstats.py index 485a479..909c9bf 100644 --- a/app/routers_v2/batstats.py +++ b/app/routers_v2/batstats.py @@ -119,7 +119,6 @@ async def get_batstats( ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -127,7 +126,6 @@ async def get_batstats( for x in all_stats: return_val['stats'].append(model_to_dict(x, recurse=False)) - db.close() return return_val @@ -166,7 +164,6 @@ async def get_player_stats( ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -175,7 +172,6 @@ async def get_player_stats( for x in all_stats: logging.debug(f'this_line: {model_to_dict(x)}') return_val = model_to_dict(all_stats[0]) - db.close() return return_val @@ -183,7 +179,6 @@ async def get_player_stats( async def post_batstats(stats: BattingStatModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post stats. This event has been logged.' @@ -232,7 +227,6 @@ async def post_batstats(stats: BattingStatModel, token: str = Depends(oauth2_sch with db.atomic(): BattingStat.bulk_create(new_stats, batch_size=15) - db.close() raise HTTPException(status_code=200, detail=f'{len(new_stats)} batting lines have been added') @@ -241,7 +235,6 @@ async def post_batstats(stats: BattingStatModel, token: str = Depends(oauth2_sch async def delete_batstat(stat_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete stats. This event has been logged.' @@ -249,11 +242,9 @@ async def delete_batstat(stat_id, token: str = Depends(oauth2_scheme)): try: this_stat = BattingStat.get_by_id(stat_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No stat found with id {stat_id}') count = this_stat.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Stat {stat_id} has been deleted') diff --git a/app/routers_v2/battingcardratings.py b/app/routers_v2/battingcardratings.py index ffe1a48..8e2d448 100644 --- a/app/routers_v2/battingcardratings.py +++ b/app/routers_v2/battingcardratings.py @@ -158,7 +158,6 @@ async def get_card_ratings( logging.debug(f"Team: {this_team} / has_guide: {this_team.has_guide}") if this_team is None or ts != this_team.team_hash() or this_team.has_guide != 1: logging.warning(f"Team_id {team_id} attempted to pull ratings") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to pull card ratings." ) @@ -195,7 +194,6 @@ async def get_card_ratings( x["player_id"] = x["battingcard"]["player"]["player_id"] del x["battingcard"], x["player"] - db.close() return Response( content=pd.DataFrame(return_vals).to_csv(index=False), media_type="text/csv" ) @@ -207,7 +205,6 @@ async def get_card_ratings( model_to_dict(x, recurse=not short_output) for x in all_ratings ], } - db.close() return return_val @@ -328,7 +325,6 @@ def get_scouting_dfs(cardset_id: list = None): name=f"Throw C", ) ) - db.close() logging.debug(f"series_list: {series_list}") return bat_df.join(series_list) @@ -340,7 +336,6 @@ async def get_card_scouting(team_id: int, ts: str): logging.debug(f"Team: {this_team} / has_guide: {this_team.has_guide}") if this_team is None or ts != this_team.team_hash() or this_team.has_guide != 1: logging.warning(f"Team_id {team_id} attempted to pull ratings") - db.close() return ( "Your team does not have the ratings guide enabled. If you have purchased a copy ping Cal to " "make sure it is enabled on your team. If you are interested you can pick it up here (thank you!): " @@ -363,7 +358,6 @@ async def get_card_scouting(team_id: int, ts: str): async def post_calc_scouting(token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to calculate card ratings." ) @@ -400,7 +394,6 @@ async def get_basic_scouting(cardset_id: list = Query(default=None)): async def post_calc_basic(token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to calculate basic ratings." ) @@ -647,20 +640,17 @@ async def post_calc_basic(token: str = Depends(oauth2_scheme)): async def get_one_rating(ratings_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to pull card ratings." ) this_rating = BattingCardRatings.get_or_none(BattingCardRatings.id == ratings_id) if this_rating is None: - db.close() raise HTTPException( status_code=404, detail=f"BattingCardRating id {ratings_id} not found" ) r_data = model_to_dict(this_rating) - db.close() return r_data @@ -673,7 +663,6 @@ async def get_player_ratings( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to pull card ratings." ) @@ -694,7 +683,6 @@ async def get_player_ratings( "count": all_ratings.count(), "ratings": [model_to_dict(x, recurse=not short_output) for x in all_ratings], } - db.close() return return_val @@ -702,7 +690,6 @@ async def get_player_ratings( async def put_ratings(ratings: RatingsList, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post card ratings." ) @@ -730,7 +717,6 @@ async def put_ratings(ratings: RatingsList, token: str = Depends(oauth2_scheme)) # Use PostgreSQL-compatible upsert helper upsert_batting_card_ratings(new_ratings, batch_size=30) - db.close() return f"Updated ratings: {updates}; new ratings: {len(new_ratings)}" @@ -738,20 +724,17 @@ async def put_ratings(ratings: RatingsList, token: str = Depends(oauth2_scheme)) async def delete_rating(ratings_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post card ratings." ) this_rating = BattingCardRatings.get_or_none(BattingCardRatings.id == ratings_id) if this_rating is None: - db.close() raise HTTPException( status_code=404, detail=f"BattingCardRating id {ratings_id} not found" ) count = this_rating.delete_instance() - db.close() if count == 1: return f"Rating {this_rating} has been deleted" diff --git a/app/routers_v2/battingcards.py b/app/routers_v2/battingcards.py index 8c8cc91..055738c 100644 --- a/app/routers_v2/battingcards.py +++ b/app/routers_v2/battingcards.py @@ -65,7 +65,6 @@ async def get_batting_cards( "count": all_cards.count(), "cards": [model_to_dict(x, recurse=not short_output) for x in all_cards], } - db.close() return return_val @@ -73,13 +72,11 @@ async def get_batting_cards( async def get_one_card(card_id: int): this_card = BattingCard.get_or_none(BattingCard.id == card_id) if this_card is None: - db.close() raise HTTPException( status_code=404, detail=f"BattingCard id {card_id} not found" ) r_card = model_to_dict(this_card) - db.close() return r_card @@ -99,7 +96,6 @@ async def get_player_cards( "count": all_cards.count(), "cards": [model_to_dict(x, recurse=not short_output) for x in all_cards], } - db.close() return return_val @@ -107,7 +103,6 @@ async def get_player_cards( async def put_cards(cards: BattingCardList, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post batting cards. This event has been logged.", @@ -157,7 +152,6 @@ async def put_cards(cards: BattingCardList, token: str = Depends(oauth2_scheme)) # Use PostgreSQL-compatible upsert helper upsert_batting_cards(new_cards, batch_size=30) - db.close() return f"Updated cards: {updates}; new cards: {len(new_cards)}" @@ -177,7 +171,6 @@ async def patch_card( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to patch batting cards. This event has been logged.", @@ -185,7 +178,6 @@ async def patch_card( this_card = BattingCard.get_or_none(BattingCard.id == card_id) if this_card is None: - db.close() raise HTTPException( status_code=404, detail=f"BattingCard id {card_id} not found" ) @@ -211,10 +203,8 @@ async def patch_card( if this_card.save() == 1: return_val = model_to_dict(this_card) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail="Well slap my ass and call me a teapot; I could not save that card", @@ -225,7 +215,6 @@ async def patch_card( async def delete_card(card_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to delete batting cards. This event has been logged.", @@ -233,13 +222,11 @@ async def delete_card(card_id: int, token: str = Depends(oauth2_scheme)): this_card = BattingCard.get_or_none(BattingCard.id == card_id) if this_card is None: - db.close() raise HTTPException( status_code=404, detail=f"BattingCard id {card_id} not found" ) count = this_card.delete_instance() - db.close() if count == 1: return f"Card {this_card} has been deleted" @@ -253,7 +240,6 @@ async def delete_card(card_id: int, token: str = Depends(oauth2_scheme)): async def delete_all_cards(token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to delete batting cards. This event has been logged.", diff --git a/app/routers_v2/cardpositions.py b/app/routers_v2/cardpositions.py index 7863bbb..206c292 100644 --- a/app/routers_v2/cardpositions.py +++ b/app/routers_v2/cardpositions.py @@ -95,7 +95,6 @@ async def get_card_positions( "count": all_pos.count(), "positions": [model_to_dict(x, recurse=not short_output) for x in all_pos], } - db.close() return return_val @@ -103,13 +102,11 @@ async def get_card_positions( async def get_one_position(position_id: int): this_pos = CardPosition.get_or_none(CardPosition.id == position_id) if this_pos is None: - db.close() raise HTTPException( status_code=404, detail=f"CardPosition id {position_id} not found" ) r_data = model_to_dict(this_pos) - db.close() return r_data @@ -117,7 +114,6 @@ async def get_one_position(position_id: int): async def put_positions(positions: PositionList, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post card positions. This event has been logged.", @@ -149,7 +145,6 @@ async def put_positions(positions: PositionList, token: str = Depends(oauth2_sch # Use PostgreSQL-compatible upsert helper upsert_card_positions(new_cards, batch_size=30) - db.close() return f"Updated cards: {updates}; new cards: {len(new_cards)}" @@ -157,7 +152,6 @@ async def put_positions(positions: PositionList, token: str = Depends(oauth2_sch async def delete_position(position_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to delete card positions. This event has been logged.", @@ -165,13 +159,11 @@ async def delete_position(position_id: int, token: str = Depends(oauth2_scheme)) this_pos = CardPosition.get_or_none(CardPosition.id == position_id) if this_pos is None: - db.close() raise HTTPException( status_code=404, detail=f"CardPosition id {position_id} not found" ) count = this_pos.delete_instance() - db.close() if count == 1: return f"Card Position {this_pos} has been deleted" diff --git a/app/routers_v2/cards.py b/app/routers_v2/cards.py index a501021..0ed2bc3 100644 --- a/app/routers_v2/cards.py +++ b/app/routers_v2/cards.py @@ -47,21 +47,18 @@ async def get_cards( try: this_team = Team.get_by_id(team_id) except Exception: - db.close() 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: - db.close() 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: - db.close() 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: @@ -108,7 +105,6 @@ async def get_cards( ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -127,7 +123,6 @@ async def get_cards( # return_val['cards'].append(model_to_dict(x)) - db.close() return return_val @@ -136,7 +131,6 @@ async def v1_cards_get_one(card_id, csv: Optional[bool] = False): try: this_card = Card.get_by_id(card_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No card found with id {card_id}') if csv: @@ -147,12 +141,10 @@ async def v1_cards_get_one(card_id, csv: Optional[bool] = False): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_card) - db.close() return return_val @@ -160,7 +152,6 @@ async def v1_cards_get_one(card_id, csv: Optional[bool] = False): async def v1_cards_post(cards: CardModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post cards. This event has been logged.' @@ -195,7 +186,6 @@ async def v1_cards_post(cards: CardModel, token: str = Depends(oauth2_scheme)): 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) - db.close() raise HTTPException(status_code=200, detail=f'{len(new_cards)} cards have been added') @@ -219,7 +209,6 @@ async def v1_cards_legal_check( 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}') - db.close() raise HTTPException( status_code=401, detail='Unauthorized' @@ -252,14 +241,12 @@ async def v1_cards_legal_check( 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}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to update card lists. This event has been logged.' ) # sheets.post_new_cards(SHEETS_AUTH, starting_id) - db.close() raise HTTPException(status_code=200, detail=f'Just sent cards to sheets starting at ID {starting_id}') @@ -267,7 +254,6 @@ async def v1_cards_post_update(starting_id: int, token: str = Depends(oauth2_sch 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}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete card lists. This event has been logged.' @@ -281,7 +267,6 @@ async def v1_cards_post_delete(del_ids: str, token: str = Depends(oauth2_scheme) 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}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to wipe teams. This event has been logged.' @@ -294,7 +279,6 @@ async def v1_cards_wipe_team(team_id: int, token: str = Depends(oauth2_scheme)): raise HTTPException(status_code=404, detail=f'Team {team_id} not found') t_query = Card.update(team=None).where(Card.team == this_team).execute() - db.close() return f'Wiped {t_query} cards' @@ -305,7 +289,6 @@ async def v1_cards_patch( roster3_id: Optional[int] = None, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch cards. This event has been logged.' @@ -313,7 +296,6 @@ async def v1_cards_patch( try: this_card = Card.get_by_id(card_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No card found with id {card_id}') if player_id is not None: @@ -338,10 +320,8 @@ async def v1_cards_patch( if this_card.save() == 1: return_val = model_to_dict(this_card) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail='Well slap my ass and call me a teapot; I could not save that rarity' @@ -352,7 +332,6 @@ async def v1_cards_patch( async def v1_cards_delete(card_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete packs. This event has been logged.' @@ -360,11 +339,9 @@ async def v1_cards_delete(card_id, token: str = Depends(oauth2_scheme)): try: this_card = Card.get_by_id(card_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No cards found with id {card_id}') count = this_card.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Card {card_id} has been deleted') diff --git a/app/routers_v2/cardsets.py b/app/routers_v2/cardsets.py index 10fb981..6ca4a38 100644 --- a/app/routers_v2/cardsets.py +++ b/app/routers_v2/cardsets.py @@ -36,7 +36,6 @@ async def get_cardsets( all_cardsets = Cardset.select().order_by(Cardset.id) if all_cardsets.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f'There are no cardsets to filter') if name is not None: @@ -56,7 +55,6 @@ async def get_cardsets( all_cardsets = all_cardsets.where(Cardset.ranked_legal == ranked_legal) if all_cardsets.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f'No cardsets found') if csv: @@ -72,7 +70,6 @@ async def get_cardsets( ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -80,7 +77,6 @@ async def get_cardsets( for x in all_cardsets: return_val['cardsets'].append(model_to_dict(x)) - db.close() return return_val @@ -115,7 +111,6 @@ async def search_cardsets( all_cardsets = all_cardsets.where(Cardset.event == this_event) except Exception as e: logging.error(f'Failed to find event {event_id}: {e}') - db.close() raise HTTPException(status_code=404, detail=f'Event id {event_id} not found') # Convert to list for sorting @@ -153,7 +148,6 @@ async def search_cardsets( 'cardsets': [model_to_dict(x) for x in limited_results] } - db.close() return return_val @@ -162,7 +156,6 @@ async def get_one_cardset(cardset_id, csv: Optional[bool] = False): try: this_cardset = Cardset.get_by_id(cardset_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No cardset found with id {cardset_id}') if csv: @@ -172,11 +165,9 @@ async def get_one_cardset(cardset_id, csv: Optional[bool] = False): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_cardset) - db.close() return return_val @@ -184,7 +175,6 @@ async def get_one_cardset(cardset_id, csv: Optional[bool] = False): async def post_cardsets(cardset: CardsetModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post cardsets. This event has been logged.' @@ -192,7 +182,6 @@ async def post_cardsets(cardset: CardsetModel, token: str = Depends(oauth2_schem dupe_set = Cardset.get_or_none(Cardset.name == cardset.name) if dupe_set: - db.close() raise HTTPException(status_code=400, detail=f'There is already a cardset using {cardset.name}') this_cardset = Cardset(**cardset.__dict__) @@ -200,7 +189,6 @@ async def post_cardsets(cardset: CardsetModel, token: str = Depends(oauth2_schem saved = this_cardset.save() if saved == 1: return_val = model_to_dict(this_cardset) - db.close() return return_val else: raise HTTPException( @@ -216,7 +204,6 @@ async def patch_cardsets( token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch cardsets. This event has been logged.' @@ -224,7 +211,6 @@ async def patch_cardsets( try: this_cardset = Cardset.get_by_id(cardset_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No cardset found with id {cardset_id}') if name is not None: @@ -242,7 +228,6 @@ async def patch_cardsets( if this_cardset.save() == 1: return_val = model_to_dict(this_cardset) - db.close() return return_val else: raise HTTPException( @@ -255,7 +240,6 @@ async def patch_cardsets( async def delete_cardsets(cardset_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete cardsets. This event has been logged.' @@ -263,11 +247,9 @@ async def delete_cardsets(cardset_id, token: str = Depends(oauth2_scheme)): try: this_cardset = Cardset.get_by_id(cardset_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No cardset found with id {cardset_id}') count = this_cardset.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Cardset {cardset_id} has been deleted') diff --git a/app/routers_v2/current.py b/app/routers_v2/current.py index a8b9545..dc5fd27 100644 --- a/app/routers_v2/current.py +++ b/app/routers_v2/current.py @@ -40,11 +40,9 @@ async def get_current(season: Optional[int] = None, csv: Optional[bool] = False) ] return_val = DataFrame(current_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(current) - db.close() return return_val @@ -53,7 +51,6 @@ async def get_one_current(current_id, csv: Optional[bool] = False): try: current = Current.get_by_id(current_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No current found with id {current_id}') if csv: @@ -63,11 +60,9 @@ async def get_one_current(current_id, csv: Optional[bool] = False): ] return_val = DataFrame(current_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(current) - db.close() return return_val @@ -75,7 +70,6 @@ async def get_one_current(current_id, csv: Optional[bool] = False): async def post_current(current: CurrentModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post current. This event has been logged.' @@ -83,7 +77,6 @@ async def post_current(current: CurrentModel, token: str = Depends(oauth2_scheme dupe_curr = Current.get_or_none(Current.season == current.season) if dupe_curr: - db.close() raise HTTPException(status_code=400, detail=f'There is already a current for season {current.season}') this_curr = Current( @@ -96,7 +89,6 @@ async def post_current(current: CurrentModel, token: str = Depends(oauth2_scheme saved = this_curr.save() if saved == 1: return_val = model_to_dict(this_curr) - db.close() 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') @@ -109,7 +101,6 @@ async def patch_current( live_scoreboard: Optional[int] = None, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch current. This event has been logged.' @@ -117,7 +108,6 @@ async def patch_current( try: current = Current.get_by_id(current_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No current found with id {current_id}') if season is not None: @@ -133,7 +123,6 @@ async def patch_current( if current.save() == 1: return_val = model_to_dict(current) - db.close() return return_val else: raise HTTPException( @@ -146,7 +135,6 @@ async def patch_current( async def delete_current(current_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete current. This event has been logged.' @@ -154,11 +142,9 @@ async def delete_current(current_id, token: str = Depends(oauth2_scheme)): try: this_curr = Current.get_by_id(current_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No current found with id {current_id}') count = this_curr.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Current {current_id} has been deleted') diff --git a/app/routers_v2/decisions.py b/app/routers_v2/decisions.py index 0e84b29..5c3d189 100644 --- a/app/routers_v2/decisions.py +++ b/app/routers_v2/decisions.py @@ -112,7 +112,6 @@ async def get_decisions( "count": all_dec.count(), "decisions": [model_to_dict(x, recurse=not short_output) for x in all_dec], } - db.close() if csv: return_vals = return_dec["decisions"] @@ -136,7 +135,6 @@ async def get_decisions( exclude = first + ["lob_all", "lob_all_rate", "lob_2outs", "rbi%"] output = output[first + [col for col in output.columns if col not in exclude]] - db.close() return Response( content=pd.DataFrame(output).to_csv(index=False), media_type="text/csv" ) @@ -189,7 +187,6 @@ async def get_decisions_for_rest( return_dec.append(this_val) - db.close() return Response( content=pd.DataFrame(return_dec).to_csv(index=False, header=False), media_type="text/csv", @@ -216,7 +213,6 @@ async def patch_decision( this_dec = Decision.get_or_none(Decision.id == decision_id) if this_dec is None: - db.close() raise HTTPException( status_code=404, detail=f"Decision ID {decision_id} not found" ) @@ -242,10 +238,8 @@ async def patch_decision( if this_dec.save() == 1: d_result = model_to_dict(this_dec) - db.close() return d_result else: - db.close() raise HTTPException( status_code=500, detail=f"Unable to patch decision {decision_id}" ) @@ -277,7 +271,6 @@ async def post_decisions(dec_list: DecisionList, token: str = Depends(oauth2_sch with db.atomic(): # Use PostgreSQL-compatible upsert helper upsert_decisions(new_dec, batch_size=10) - db.close() return f"Inserted {len(new_dec)} decisions" @@ -290,13 +283,11 @@ async def delete_decision(decision_id: int, token: str = Depends(oauth2_scheme)) this_dec = Decision.get_or_none(Decision.id == decision_id) if this_dec is None: - db.close() raise HTTPException( status_code=404, detail=f"Decision ID {decision_id} not found" ) count = this_dec.delete_instance() - db.close() if count == 1: return f"Decision {decision_id} has been deleted" @@ -314,11 +305,9 @@ async def delete_decisions_game(game_id: int, token: str = Depends(oauth2_scheme this_game = StratGame.get_or_none(StratGame.id == game_id) if not this_game: - db.close() raise HTTPException(status_code=404, detail=f"Game ID {game_id} not found") count = Decision.delete().where(Decision.game == this_game).execute() - db.close() if count > 0: return f"Deleted {count} decisions matching Game ID {game_id}" diff --git a/app/routers_v2/events.py b/app/routers_v2/events.py index 0fcad4c..3674426 100644 --- a/app/routers_v2/events.py +++ b/app/routers_v2/events.py @@ -54,7 +54,6 @@ async def v1_events_get( ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -62,7 +61,6 @@ async def v1_events_get( for x in all_events: return_val['events'].append(model_to_dict(x)) - db.close() return return_val @@ -71,7 +69,6 @@ async def v1_events_get_one(event_id, csv: Optional[bool] = False): try: this_event = Event.get_by_id(event_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No event found with id {event_id}') if csv: @@ -82,12 +79,10 @@ async def v1_events_get_one(event_id, csv: Optional[bool] = False): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_event) - db.close() return return_val @@ -95,7 +90,6 @@ async def v1_events_get_one(event_id, csv: Optional[bool] = False): async def v1_events_post(event: EventModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post events. This event has been logged.' @@ -103,7 +97,6 @@ async def v1_events_post(event: EventModel, token: str = Depends(oauth2_scheme)) dupe_event = Event.get_or_none(Event.name == event.name) if dupe_event: - db.close() raise HTTPException(status_code=400, detail=f'There is already an event using {event.name}') this_event = Event( @@ -118,10 +111,8 @@ async def v1_events_post(event: EventModel, token: str = Depends(oauth2_scheme)) saved = this_event.save() if saved == 1: return_val = model_to_dict(this_event) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail='Well slap my ass and call me a teapot; I could not save that cardset' @@ -135,7 +126,6 @@ async def v1_events_patch( token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch events. This event has been logged.' @@ -143,7 +133,6 @@ async def v1_events_patch( try: this_event = Event.get_by_id(event_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No event found with id {event_id}') if name is not None: @@ -161,10 +150,8 @@ async def v1_events_patch( if this_event.save() == 1: return_val = model_to_dict(this_event) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail='Well slap my ass and call me a teapot; I could not save that event' @@ -175,7 +162,6 @@ async def v1_events_patch( async def v1_events_delete(event_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete events. This event has been logged.' @@ -183,11 +169,9 @@ async def v1_events_delete(event_id, token: str = Depends(oauth2_scheme)): try: this_event = Event.get_by_id(event_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No event found with id {event_id}') count = this_event.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Event {event_id} has been deleted') diff --git a/app/routers_v2/gamerewards.py b/app/routers_v2/gamerewards.py index 9f19d65..20e6d68 100644 --- a/app/routers_v2/gamerewards.py +++ b/app/routers_v2/gamerewards.py @@ -54,7 +54,6 @@ async def v1_gamerewards_get( ]) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -62,7 +61,6 @@ async def v1_gamerewards_get( for x in all_rewards: return_val['gamerewards'].append(model_to_dict(x)) - db.close() return return_val @@ -71,7 +69,6 @@ async def v1_gamerewards_get_one(gamereward_id, csv: Optional[bool] = None): try: this_game_reward = GameRewards.get_by_id(gamereward_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No game reward found with id {gamereward_id}') if csv: @@ -82,12 +79,10 @@ async def v1_gamerewards_get_one(gamereward_id, csv: Optional[bool] = None): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_game_reward) - db.close() return return_val @@ -95,7 +90,6 @@ async def v1_gamerewards_get_one(gamereward_id, csv: Optional[bool] = None): async def v1_gamerewards_post(game_reward: GameRewardModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post game rewards. This event has been logged.' @@ -111,10 +105,8 @@ async def v1_gamerewards_post(game_reward: GameRewardModel, token: str = Depends saved = this_award.save() if saved == 1: return_val = model_to_dict(this_award) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail='Well slap my ass and call me a teapot; I could not save that roster' @@ -127,7 +119,6 @@ async def v1_gamerewards_patch( 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}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch gamerewards. This event has been logged.' @@ -135,7 +126,6 @@ async def v1_gamerewards_patch( try: this_game_reward = GameRewards.get_by_id(game_reward_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No game reward found with id {game_reward_id}') if name is not None: @@ -158,7 +148,6 @@ async def v1_gamerewards_patch( if this_game_reward.save() == 1: return_val = model_to_dict(this_game_reward) - db.close() return return_val else: raise HTTPException( @@ -171,7 +160,6 @@ async def v1_gamerewards_patch( async def v1_gamerewards_delete(gamereward_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete awards. This event has been logged.' @@ -179,11 +167,9 @@ async def v1_gamerewards_delete(gamereward_id, token: str = Depends(oauth2_schem try: this_award = GameRewards.get_by_id(gamereward_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No award found with id {gamereward_id}') count = this_award.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Game Reward {gamereward_id} has been deleted') diff --git a/app/routers_v2/gauntletrewards.py b/app/routers_v2/gauntletrewards.py index 03127b6..9f76bf5 100644 --- a/app/routers_v2/gauntletrewards.py +++ b/app/routers_v2/gauntletrewards.py @@ -55,7 +55,6 @@ async def v1_gauntletreward_get( for x in all_rewards: return_val["rewards"].append(model_to_dict(x)) - db.close() return return_val @@ -64,14 +63,12 @@ async def v1_gauntletreward_get_one(gauntletreward_id): try: this_reward = GauntletReward.get_by_id(gauntletreward_id) except Exception: - db.close() raise HTTPException( status_code=404, detail=f"No gauntlet reward found with id {gauntletreward_id}", ) return_val = model_to_dict(this_reward) - db.close() return return_val @@ -87,7 +84,6 @@ async def v1_gauntletreward_patch( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to patch gauntlet rewards. This event has been logged.", @@ -95,7 +91,6 @@ async def v1_gauntletreward_patch( this_reward = GauntletReward.get_or_none(GauntletReward.id == gauntletreward_id) if this_reward is None: - db.close() raise KeyError(f"Gauntlet Reward ID {gauntletreward_id} not found") if gauntlet_id is not None: @@ -111,10 +106,8 @@ async def v1_gauntletreward_patch( if this_reward.save(): r_curr = model_to_dict(this_reward) - db.close() return r_curr else: - db.close() raise DatabaseError(f"Unable to patch gauntlet reward {gauntletreward_id}") @@ -124,7 +117,6 @@ async def v1_gauntletreward_post( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post gauntlets. This event has been logged.", @@ -137,7 +129,6 @@ async def v1_gauntletreward_post( with db.atomic(): # Use PostgreSQL-compatible upsert helper upsert_gauntlet_rewards(all_rewards, batch_size=15) - db.close() return f"Inserted {len(all_rewards)} gauntlet rewards" diff --git a/app/routers_v2/gauntletruns.py b/app/routers_v2/gauntletruns.py index e67859c..f664319 100644 --- a/app/routers_v2/gauntletruns.py +++ b/app/routers_v2/gauntletruns.py @@ -82,7 +82,6 @@ async def get_gauntletruns( for x in all_gauntlets: return_val['runs'].append(model_to_dict(x)) - db.close() return return_val @@ -91,11 +90,9 @@ async def get_one_gauntletrun(gauntletrun_id): try: this_gauntlet = GauntletRun.get_by_id(gauntletrun_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No gauntlet found with id {gauntletrun_id}') return_val = model_to_dict(this_gauntlet) - db.close() return return_val @@ -106,7 +103,6 @@ async def patch_gauntletrun( token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch gauntlet runs. This event has been logged.' @@ -114,7 +110,6 @@ async def patch_gauntletrun( this_run = GauntletRun.get_or_none(GauntletRun.id == gauntletrun_id) if this_run is None: - db.close() raise KeyError(f'Gauntlet Run ID {gauntletrun_id} not found') if team_id is not None: @@ -138,10 +133,8 @@ async def patch_gauntletrun( if this_run.save(): r_curr = model_to_dict(this_run) - db.close() return r_curr else: - db.close() raise DatabaseError(f'Unable to patch gauntlet run {gauntletrun_id}') @@ -149,7 +142,6 @@ async def patch_gauntletrun( async def post_gauntletrun(gauntletrun: GauntletRunModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post gauntlets. This event has been logged.' @@ -169,10 +161,8 @@ async def post_gauntletrun(gauntletrun: GauntletRunModel, token: str = Depends(o if this_run.save(): r_run = model_to_dict(this_run) - db.close() return r_run else: - db.close() raise DatabaseError(f'Unable to post gauntlet run') diff --git a/app/routers_v2/mlbplayers.py b/app/routers_v2/mlbplayers.py index b6b59ed..788ed43 100644 --- a/app/routers_v2/mlbplayers.py +++ b/app/routers_v2/mlbplayers.py @@ -111,14 +111,12 @@ async def get_players( if csv: return_val = query_to_csv(all_players) - db.close() return Response(content=return_val, media_type="text/csv") return_val = { "count": all_players.count(), "players": [model_to_dict(x) for x in all_players], } - db.close() return return_val @@ -126,13 +124,11 @@ async def get_players( async def get_one_player(player_id: int): this_player = MlbPlayer.get_or_none(MlbPlayer.id == player_id) if this_player is None: - db.close() raise HTTPException( status_code=404, detail=f"MlbPlayer id {player_id} not found" ) r_data = model_to_dict(this_player) - db.close() return r_data @@ -150,7 +146,6 @@ async def patch_player( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to patch mlb players. This event has been logged.", @@ -158,7 +153,6 @@ async def patch_player( this_player = MlbPlayer.get_or_none(MlbPlayer.id == player_id) if this_player is None: - db.close() raise HTTPException( status_code=404, detail=f"MlbPlayer id {player_id} not found" ) @@ -180,10 +174,8 @@ async def patch_player( if this_player.save() == 1: return_val = model_to_dict(this_player) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail="Well slap my ass and call me a teapot; I could not save that player", @@ -194,7 +186,6 @@ async def patch_player( async def post_players(players: PlayerList, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post mlb players. This event has been logged.", @@ -209,7 +200,6 @@ async def post_players(players: PlayerList, token: str = Depends(oauth2_scheme)) | (MlbPlayer.key_bbref == x.key_bbref) ) if dupes.count() > 0: - db.close() raise HTTPException( status_code=400, detail=f"{x.first_name} {x.last_name} has a key already in the database", @@ -221,7 +211,6 @@ async def post_players(players: PlayerList, token: str = Depends(oauth2_scheme)) # Use PostgreSQL-compatible upsert helper # Note: Duplicate check is already done above, so this is effectively just insert upsert_mlb_players(new_players, batch_size=15) - db.close() return f"Inserted {len(new_players)} new MLB players" @@ -230,7 +219,6 @@ async def post_players(players: PlayerList, token: str = Depends(oauth2_scheme)) async def post_one_player(player: PlayerModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post mlb players. This event has been logged.", @@ -245,7 +233,6 @@ async def post_one_player(player: PlayerModel, token: str = Depends(oauth2_schem logging.info(f"POST /mlbplayers/one - dupes found:") for x in dupes: logging.info(f"{x}") - db.close() raise HTTPException( status_code=400, detail=f"{player.first_name} {player.last_name} has a key already in the database", @@ -255,7 +242,6 @@ async def post_one_player(player: PlayerModel, token: str = Depends(oauth2_schem saved = new_player.save() if saved == 1: return_val = model_to_dict(new_player) - db.close() return return_val else: raise HTTPException( @@ -268,7 +254,6 @@ async def post_one_player(player: PlayerModel, token: str = Depends(oauth2_schem async def delete_player(player_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to delete mlb players. This event has been logged.", @@ -276,13 +261,11 @@ async def delete_player(player_id: int, token: str = Depends(oauth2_scheme)): this_player = MlbPlayer.get_or_none(MlbPlayer.id == player_id) if this_player is None: - db.close() raise HTTPException( status_code=404, detail=f"MlbPlayer id {player_id} not found" ) count = this_player.delete_instance() - db.close() if count == 1: raise HTTPException( @@ -301,7 +284,6 @@ async def update_columns( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to update mlb players. This event has been logged.", @@ -327,7 +309,6 @@ async def update_columns( logging.info(f"Updated {count} batting cards for {x.first_name} {x.last_name}") update_card_urls(x) - db.close() return f"Updated {total_count} batting cards" @@ -338,7 +319,6 @@ async def update_names( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to update mlb players. This event has been logged.", @@ -360,7 +340,6 @@ async def update_names( logging.info(f"Update {count} player records for {x.first_name} {x.last_name}") update_card_urls(x) - db.close() return f"Updated {total_count} names" diff --git a/app/routers_v2/notifications.py b/app/routers_v2/notifications.py index 5708f4b..233d5aa 100644 --- a/app/routers_v2/notifications.py +++ b/app/routers_v2/notifications.py @@ -38,7 +38,6 @@ async def get_notifs( all_notif = Notification.select().order_by(Notification.id) if all_notif.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f'There are no notifications to filter') if created_after is not None: @@ -66,7 +65,6 @@ async def get_notifs( ]) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -74,7 +72,6 @@ async def get_notifs( for x in all_notif: return_val['notifs'].append(model_to_dict(x)) - db.close() return return_val @@ -83,7 +80,6 @@ async def get_one_notif(notif_id, csv: Optional[bool] = None): try: this_notif = Notification.get_by_id(notif_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No notification found with id {notif_id}') if csv: @@ -94,12 +90,10 @@ async def get_one_notif(notif_id, csv: Optional[bool] = None): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_notif) - db.close() return return_val @@ -107,7 +101,6 @@ async def get_one_notif(notif_id, csv: Optional[bool] = None): async def post_notif(notif: NotifModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post notifications. This event has been logged.' @@ -126,10 +119,8 @@ async def post_notif(notif: NotifModel, token: str = Depends(oauth2_scheme)): saved = this_notif.save() if saved == 1: return_val = model_to_dict(this_notif) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail='Well slap my ass and call me a teapot; I could not save that notification' @@ -143,7 +134,6 @@ async def patch_notif( ack: Optional[bool] = None, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch notifications. This event has been logged.' @@ -151,7 +141,6 @@ async def patch_notif( try: this_notif = Notification.get_by_id(notif_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No notification found with id {notif_id}') if title is not None: @@ -171,7 +160,6 @@ async def patch_notif( if this_notif.save() == 1: return_val = model_to_dict(this_notif) - db.close() return return_val else: raise HTTPException( @@ -184,7 +172,6 @@ async def patch_notif( async def delete_notif(notif_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete notifications. This event has been logged.' @@ -192,11 +179,9 @@ async def delete_notif(notif_id, token: str = Depends(oauth2_scheme)): try: this_notif = Notification.get_by_id(notif_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No notification found with id {notif_id}') count = this_notif.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Notification {notif_id} has been deleted') diff --git a/app/routers_v2/packs.py b/app/routers_v2/packs.py index 6a1af12..ba4ada0 100644 --- a/app/routers_v2/packs.py +++ b/app/routers_v2/packs.py @@ -41,21 +41,18 @@ async def get_packs( all_packs = Pack.select() if all_packs.count() == 0: - db.close() 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: - db.close() 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: - db.close() 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) @@ -63,7 +60,6 @@ async def get_packs( try: this_pack_team = Team.get_by_id(pack_team_id) except Exception: - db.close() 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: @@ -73,7 +69,6 @@ async def get_packs( try: this_pack_cardset = Cardset.get_by_id(pack_cardset_id) except Exception: - db.close() 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: @@ -103,7 +98,6 @@ async def get_packs( ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -111,7 +105,6 @@ async def get_packs( for x in all_packs: return_val['packs'].append(model_to_dict(x)) - db.close() return return_val @@ -120,7 +113,6 @@ async def get_one_pack(pack_id, csv: Optional[bool] = False): try: this_pack = Pack.get_by_id(pack_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No pack found with id {pack_id}') if csv: @@ -131,12 +123,10 @@ async def get_one_pack(pack_id, csv: Optional[bool] = False): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_pack) - db.close() return return_val @@ -144,7 +134,6 @@ async def get_one_pack(pack_id, csv: Optional[bool] = False): async def post_pack(packs: PackModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post packs. This event has been logged.' @@ -163,7 +152,6 @@ async def post_pack(packs: PackModel, token: str = Depends(oauth2_scheme)): with db.atomic(): Pack.bulk_create(new_packs, batch_size=15) - db.close() raise HTTPException(status_code=200, detail=f'{len(new_packs)} packs have been added') @@ -172,7 +160,6 @@ async def post_pack(packs: PackModel, token: str = Depends(oauth2_scheme)): async def post_one_pack(pack: PackPydantic, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post packs. This event has been logged.' @@ -189,7 +176,6 @@ async def post_one_pack(pack: PackPydantic, token: str = Depends(oauth2_scheme)) saved = this_pack.save() if saved == 1: return_val = model_to_dict(this_pack) - db.close() return return_val else: raise HTTPException( @@ -204,7 +190,6 @@ async def patch_pack( 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}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch packs. This event has been logged.' @@ -212,7 +197,6 @@ async def patch_pack( try: this_pack = Pack.get_by_id(pack_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No pack found with id {pack_id}') if team_id is not None: @@ -237,7 +221,6 @@ async def patch_pack( if this_pack.save() == 1: return_val = model_to_dict(this_pack) - db.close() return return_val else: raise HTTPException( @@ -250,7 +233,6 @@ async def patch_pack( async def delete_pack(pack_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete packs. This event has been logged.' @@ -258,11 +240,9 @@ async def delete_pack(pack_id, token: str = Depends(oauth2_scheme)): try: this_pack = Pack.get_by_id(pack_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No packs found with id {pack_id}') count = this_pack.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Pack {pack_id} has been deleted') diff --git a/app/routers_v2/packtypes.py b/app/routers_v2/packtypes.py index c0ad637..df3f7d7 100644 --- a/app/routers_v2/packtypes.py +++ b/app/routers_v2/packtypes.py @@ -34,7 +34,6 @@ async def get_packtypes( all_packtypes = PackType.select().order_by(PackType.id) if all_packtypes.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f'There are no packtypes to filter') if name is not None: @@ -60,7 +59,6 @@ async def get_packtypes( ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -68,7 +66,6 @@ async def get_packtypes( for x in all_packtypes: return_val['packtypes'].append(model_to_dict(x)) - db.close() return return_val @@ -77,7 +74,6 @@ async def get_one_packtype(packtype_id, csv: Optional[bool] = False): try: this_packtype = PackType.get_by_id(packtype_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No packtype found with id {packtype_id}') if csv: @@ -87,12 +83,10 @@ async def get_one_packtype(packtype_id, csv: Optional[bool] = False): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_packtype) - db.close() return return_val @@ -100,7 +94,6 @@ async def get_one_packtype(packtype_id, csv: Optional[bool] = False): async def post_packtypes(packtype: PacktypeModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post packtypes. This event has been logged.' @@ -108,7 +101,6 @@ async def post_packtypes(packtype: PacktypeModel, token: str = Depends(oauth2_sc dupe_packtype = PackType.get_or_none(PackType.name == packtype.name) if dupe_packtype: - db.close() raise HTTPException(status_code=400, detail=f'There is already a packtype using {packtype.name}') this_packtype = PackType( @@ -122,7 +114,6 @@ async def post_packtypes(packtype: PacktypeModel, token: str = Depends(oauth2_sc saved = this_packtype.save() if saved == 1: return_val = model_to_dict(this_packtype) - db.close() return return_val else: raise HTTPException( @@ -137,7 +128,6 @@ async def patch_packtype( cost: Optional[int] = None, available: Optional[bool] = None, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch packtypes. This event has been logged.' @@ -145,7 +135,6 @@ async def patch_packtype( try: this_packtype = PackType.get_by_id(packtype_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No packtype found with id {packtype_id}') if name is not None: @@ -161,7 +150,6 @@ async def patch_packtype( if this_packtype.save() == 1: return_val = model_to_dict(this_packtype) - db.close() return return_val else: raise HTTPException( @@ -174,7 +162,6 @@ async def patch_packtype( async def delete_packtype(packtype_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete packtypes. This event has been logged.' @@ -182,11 +169,9 @@ async def delete_packtype(packtype_id, token: str = Depends(oauth2_scheme)): try: this_packtype = PackType.get_by_id(packtype_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No packtype found with id {packtype_id}') count = this_packtype.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Packtype {packtype_id} has been deleted') diff --git a/app/routers_v2/paperdex.py b/app/routers_v2/paperdex.py index 957e733..4df6258 100644 --- a/app/routers_v2/paperdex.py +++ b/app/routers_v2/paperdex.py @@ -34,7 +34,6 @@ async def get_paperdex( all_dex = Paperdex.select().join(Player).join(Cardset).order_by(Paperdex.id) if all_dex.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f'There are no paperdex to filter') if team_id is not None: @@ -67,7 +66,6 @@ async def get_paperdex( ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -75,7 +73,6 @@ async def get_paperdex( for x in all_dex: return_val['paperdex'].append(model_to_dict(x, recurse=not flat)) - db.close() return return_val @@ -84,7 +81,6 @@ async def get_one_paperdex(paperdex_id, csv: Optional[bool] = False): try: this_dex = Paperdex.get_by_id(paperdex_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No paperdex found with id {paperdex_id}') if csv: @@ -94,12 +90,10 @@ async def get_one_paperdex(paperdex_id, csv: Optional[bool] = False): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_dex) - db.close() return return_val @@ -107,7 +101,6 @@ async def get_one_paperdex(paperdex_id, csv: Optional[bool] = False): async def post_paperdex(paperdex: PaperdexModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post paperdex. This event has been logged.' @@ -116,7 +109,6 @@ async def post_paperdex(paperdex: PaperdexModel, token: str = Depends(oauth2_sch 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) - db.close() return return_val this_dex = Paperdex( @@ -128,7 +120,6 @@ async def post_paperdex(paperdex: PaperdexModel, token: str = Depends(oauth2_sch saved = this_dex.save() if saved == 1: return_val = model_to_dict(this_dex) - db.close() return return_val else: raise HTTPException( @@ -143,7 +134,6 @@ async def patch_paperdex( token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch paperdex. This event has been logged.' @@ -151,7 +141,6 @@ async def patch_paperdex( try: this_dex = Paperdex.get_by_id(paperdex_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No paperdex found with id {paperdex_id}') if team_id is not None: @@ -163,7 +152,6 @@ async def patch_paperdex( if this_dex.save() == 1: return_val = model_to_dict(this_dex) - db.close() return return_val else: raise HTTPException( @@ -176,7 +164,6 @@ async def patch_paperdex( async def delete_paperdex(paperdex_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete rewards. This event has been logged.' @@ -184,11 +171,9 @@ async def delete_paperdex(paperdex_id, token: str = Depends(oauth2_scheme)): try: this_dex = Paperdex.get_by_id(paperdex_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No paperdex found with id {paperdex_id}') count = this_dex.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Paperdex {this_dex} has been deleted') @@ -200,7 +185,6 @@ async def delete_paperdex(paperdex_id, token: str = Depends(oauth2_scheme)): async def wipe_ai_paperdex(token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='Unauthorized' diff --git a/app/routers_v2/pitchingcardratings.py b/app/routers_v2/pitchingcardratings.py index 80b589d..fea857e 100644 --- a/app/routers_v2/pitchingcardratings.py +++ b/app/routers_v2/pitchingcardratings.py @@ -153,7 +153,6 @@ async def get_card_ratings( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to pull card ratings." ) @@ -177,7 +176,6 @@ async def get_card_ratings( if csv: return_val = query_to_csv(all_ratings) - db.close() return Response(content=return_val, media_type="text/csv") else: @@ -187,7 +185,6 @@ async def get_card_ratings( model_to_dict(x, recurse=not short_output) for x in all_ratings ], } - db.close() return return_val @@ -246,7 +243,6 @@ def get_scouting_dfs(cardset_id: list = None): dict([(x.player.player_id, x.error) for x in positions]), name=f"Error P" ), ] - db.close() logging.debug(f"series_list: {series_list}") return pit_df.join(series_list) @@ -258,7 +254,6 @@ async def get_card_scouting(team_id: int, ts: str): logging.debug(f"Team: {this_team} / has_guide: {this_team.has_guide}") if this_team is None or ts != this_team.team_hash() or this_team.has_guide != 1: logging.warning(f"Team_id {team_id} attempted to pull ratings") - db.close() return ( "Your team does not have the ratings guide enabled. If you have purchased a copy ping Cal to " "make sure it is enabled on your team. If you are interested you can pick it up here (thank you!): " @@ -281,7 +276,6 @@ async def get_card_scouting(team_id: int, ts: str): async def post_calc_scouting(token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to calculate card ratings." ) @@ -318,7 +312,6 @@ async def get_basic_scouting(): async def post_calc_basic(token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to calculate basic ratings." ) @@ -498,20 +491,17 @@ async def post_calc_basic(token: str = Depends(oauth2_scheme)): async def get_one_rating(ratings_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to pull card ratings." ) this_rating = PitchingCardRatings.get_or_none(PitchingCardRatings.id == ratings_id) if this_rating is None: - db.close() raise HTTPException( status_code=404, detail=f"PitchingCardRating id {ratings_id} not found" ) r_data = model_to_dict(this_rating) - db.close() return r_data @@ -535,7 +525,6 @@ async def get_player_ratings( "count": all_ratings.count(), "ratings": [model_to_dict(x, recurse=not short_output) for x in all_ratings], } - db.close() return return_val @@ -543,7 +532,6 @@ async def get_player_ratings( async def put_ratings(ratings: RatingsList, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post card ratings." ) @@ -571,7 +559,6 @@ async def put_ratings(ratings: RatingsList, token: str = Depends(oauth2_scheme)) # Use PostgreSQL-compatible upsert helper upsert_pitching_card_ratings(new_ratings, batch_size=30) - db.close() return f"Updated ratings: {updates}; new ratings: {len(new_ratings)}" @@ -579,20 +566,17 @@ async def put_ratings(ratings: RatingsList, token: str = Depends(oauth2_scheme)) async def delete_rating(ratings_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post card ratings." ) this_rating = PitchingCardRatings.get_or_none(PitchingCardRatings.id == ratings_id) if this_rating is None: - db.close() raise HTTPException( status_code=404, detail=f"PitchingCardRating id {ratings_id} not found" ) count = this_rating.delete_instance() - db.close() if count == 1: return f"Rating {this_rating} has been deleted" diff --git a/app/routers_v2/pitchingcards.py b/app/routers_v2/pitchingcards.py index 9bc060b..43e238c 100644 --- a/app/routers_v2/pitchingcards.py +++ b/app/routers_v2/pitchingcards.py @@ -62,7 +62,6 @@ async def get_pitching_cards( "count": all_cards.count(), "cards": [model_to_dict(x, recurse=not short_output) for x in all_cards], } - db.close() return return_val @@ -70,13 +69,11 @@ async def get_pitching_cards( async def get_one_card(card_id: int): this_card = PitchingCard.get_or_none(PitchingCard.id == card_id) if this_card is None: - db.close() raise HTTPException( status_code=404, detail=f"PitchingCard id {card_id} not found" ) r_card = model_to_dict(this_card) - db.close() return r_card @@ -96,7 +93,6 @@ async def get_player_cards( "count": all_cards.count(), "cards": [model_to_dict(x, recurse=not short_output) for x in all_cards], } - db.close() return return_val @@ -104,7 +100,6 @@ async def get_player_cards( async def put_cards(cards: PitchingCardList, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post pitching cards. This event has been logged.", @@ -153,7 +148,6 @@ async def put_cards(cards: PitchingCardList, token: str = Depends(oauth2_scheme) # Use PostgreSQL-compatible upsert helper upsert_pitching_cards(new_cards, batch_size=30) - db.close() return f"Updated cards: {updates}; new cards: {len(new_cards)}" @@ -171,7 +165,6 @@ async def patch_card( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to patch pitching cards. This event has been logged.", @@ -179,7 +172,6 @@ async def patch_card( this_card = PitchingCard.get_or_none(PitchingCard.id == card_id) if this_card is None: - db.close() raise HTTPException( status_code=404, detail=f"PitchingCard id {card_id} not found" ) @@ -201,10 +193,8 @@ async def patch_card( if this_card.save() == 1: return_val = model_to_dict(this_card) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail="Well slap my ass and call me a teapot; I could not save that card", @@ -215,7 +205,6 @@ async def patch_card( async def delete_card(card_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to delete pitching cards. This event has been logged.", @@ -223,11 +212,9 @@ async def delete_card(card_id: int, token: str = Depends(oauth2_scheme)): this_card = PitchingCard.get_or_none(PitchingCard.id == card_id) if this_card is None: - db.close() raise HTTPException(status_code=404, detail=f"Pitching id {card_id} not found") count = this_card.delete_instance() - db.close() if count == 1: return f"Card {this_card} has been deleted" @@ -241,7 +228,6 @@ async def delete_card(card_id: int, token: str = Depends(oauth2_scheme)): async def delete_all_cards(token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to delete pitching cards. This event has been logged.", diff --git a/app/routers_v2/pitstats.py b/app/routers_v2/pitstats.py index 58a564d..5219ca0 100644 --- a/app/routers_v2/pitstats.py +++ b/app/routers_v2/pitstats.py @@ -108,7 +108,6 @@ async def get_pit_stats( ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -116,7 +115,6 @@ async def get_pit_stats( for x in all_stats: return_val['stats'].append(model_to_dict(x, recurse=False)) - db.close() return return_val @@ -124,7 +122,6 @@ async def get_pit_stats( async def post_pitstat(stats: PitchingStatModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post stats. This event has been logged.' @@ -164,7 +161,6 @@ async def post_pitstat(stats: PitchingStatModel, token: str = Depends(oauth2_sch with db.atomic(): PitchingStat.bulk_create(new_stats, batch_size=15) - db.close() raise HTTPException(status_code=200, detail=f'{len(new_stats)} pitching lines have been added') @@ -173,7 +169,6 @@ async def post_pitstat(stats: PitchingStatModel, token: str = Depends(oauth2_sch async def delete_pitstat(stat_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete stats. This event has been logged.' @@ -181,11 +176,9 @@ async def delete_pitstat(stat_id, token: str = Depends(oauth2_scheme)): try: this_stat = PitchingStat.get_by_id(stat_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No stat found with id {stat_id}') count = this_stat.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Stat {stat_id} has been deleted') diff --git a/app/routers_v2/players.py b/app/routers_v2/players.py index 37f20d6..bd0cba0 100644 --- a/app/routers_v2/players.py +++ b/app/routers_v2/players.py @@ -152,7 +152,6 @@ async def get_players( ): all_players = Player.select() if all_players.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f"There are no players to filter") if name is not None: @@ -239,7 +238,6 @@ async def get_players( if csv: card_vals = [model_to_dict(x) for x in all_players] - db.close() for x in card_vals: x["player_name"] = x["p_name"] @@ -328,7 +326,6 @@ async def get_players( # return_val['players'].append(model_to_dict(x, recurse=not flat)) - db.close() return return_val @@ -479,7 +476,6 @@ async def get_random_player( ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type="text/csv") else: @@ -497,7 +493,6 @@ async def get_random_player( return_val["players"].append(this_record) # return_val['players'].append(model_to_dict(x)) - db.close() return return_val @@ -591,7 +586,6 @@ async def search_players( return_val["players"].append(this_record) - db.close() return return_val @@ -600,7 +594,6 @@ async def get_one_player(player_id, csv: Optional[bool] = False): try: this_player = Player.get_by_id(player_id) except Exception: - db.close() raise HTTPException( status_code=404, detail=f"No player found with id {player_id}" ) @@ -660,7 +653,6 @@ async def get_one_player(player_id, csv: Optional[bool] = False): ] ) - db.close() return Response(content=return_val, media_type="text/csv") else: return_val = model_to_dict(this_player) @@ -668,7 +660,6 @@ async def get_one_player(player_id, csv: Optional[bool] = False): return_val["paperdex"] = {"count": this_dex.count(), "paperdex": []} for x in this_dex: return_val["paperdex"]["paperdex"].append(model_to_dict(x, recurse=False)) - db.close() return return_val @@ -686,7 +677,6 @@ async def get_batter_card( try: this_player = Player.get_by_id(player_id) except Exception: - db.close() raise HTTPException( status_code=404, detail=f"No player found with id {player_id}" ) @@ -701,7 +691,6 @@ async def get_batter_card( ) and html is False ): - db.close() return FileResponse( path=f"storage/cards/cardset-{this_player.cardset.id}/{card_type}/{player_id}-{d}-v{variant}.png", media_type="image/png", @@ -788,7 +777,6 @@ async def get_batter_card( html_response = templates.TemplateResponse("player_card.html", card_data) if html: - db.close() return html_response updates = 0 @@ -843,7 +831,6 @@ async def get_batter_card( # save_as=f'{player_id}-{d}-v{variant}.png' # ) - db.close() return FileResponse(path=file_path, media_type="image/png", headers=headers) @@ -882,7 +869,6 @@ async def v1_players_patch( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to patch players. This event has been logged.", @@ -891,7 +877,6 @@ async def v1_players_patch( try: this_player = Player.get_by_id(player_id) except Exception: - db.close() raise HTTPException( status_code=404, detail=f"No player found with id {player_id}" ) @@ -915,7 +900,6 @@ async def v1_players_patch( try: this_cardset = Cardset.get_by_id(cardset_id) except Exception: - db.close() raise HTTPException( status_code=404, detail=f"No cardset found with id {cardset_id}" ) @@ -924,7 +908,6 @@ async def v1_players_patch( try: this_rarity = Rarity.get_by_id(rarity_id) except Exception: - db.close() raise HTTPException( status_code=404, detail=f"No rarity found with id {rarity_id}" ) @@ -986,7 +969,6 @@ async def v1_players_patch( if this_player.save() == 1: return_val = model_to_dict(this_player) - db.close() return return_val else: raise HTTPException( @@ -999,7 +981,6 @@ async def v1_players_patch( async def put_players(players: PlayerModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post players. This event has been logged.", @@ -1068,7 +1049,6 @@ async def put_players(players: PlayerModel, token: str = Depends(oauth2_scheme)) with db.atomic(): # Use PostgreSQL-compatible upsert helper (preserves SQLite compatibility) upsert_players(new_players, batch_size=15) - db.close() # sheets.update_all_players(SHEETS_AUTH) raise HTTPException( @@ -1080,7 +1060,6 @@ async def put_players(players: PlayerModel, token: str = Depends(oauth2_scheme)) async def post_players(new_player: PlayerPydantic, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post players. This event has been logged.", @@ -1091,7 +1070,6 @@ async def post_players(new_player: PlayerPydantic, token: str = Depends(oauth2_s & (Player.cardset_id == new_player.cardset_id) ) if dupe_query.count() != 0: - db.close() raise HTTPException( status_code=400, detail=f"This appears to be a duplicate with player {dupe_query[0].player_id}", @@ -1104,7 +1082,6 @@ async def post_players(new_player: PlayerPydantic, token: str = Depends(oauth2_s p_id = Player.insert(new_player.dict()).execute() return_val = model_to_dict(Player.get_by_id(p_id)) - db.close() return return_val @@ -1114,7 +1091,6 @@ async def post_image_reset( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to modify players. This event has been logged.", @@ -1122,7 +1098,6 @@ async def post_image_reset( this_player = Player.get_or_none(Player.player_id == player_id) if this_player is None: - db.close() raise HTTPException(status_code=404, detail=f"Player ID {player_id} not found") now = datetime.datetime.now() @@ -1143,7 +1118,6 @@ async def post_image_reset( this_player.save() r_player = model_to_dict(this_player) - db.close() return r_player @@ -1151,7 +1125,6 @@ async def post_image_reset( async def delete_player(player_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to delete players. This event has been logged.", @@ -1160,13 +1133,11 @@ async def delete_player(player_id, token: str = Depends(oauth2_scheme)): try: this_player = Player.get_by_id(player_id) except Exception: - db.close() raise HTTPException( status_code=404, detail=f"No player found with id {player_id}" ) count = this_player.delete_instance() - db.close() if count == 1: raise HTTPException( diff --git a/app/routers_v2/rarity.py b/app/routers_v2/rarity.py index a0b756a..7635f78 100644 --- a/app/routers_v2/rarity.py +++ b/app/routers_v2/rarity.py @@ -31,7 +31,6 @@ async def get_rarities(value: Optional[int] = None, name: Optional[str] = None, all_rarities = Rarity.select().order_by(Rarity.id) if all_rarities.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f'There are no rarities to filter') if value is not None: @@ -44,7 +43,6 @@ 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: - db.close() raise HTTPException(status_code=404, detail=f'No rarities found') if csv: @@ -57,7 +55,6 @@ async def get_rarities(value: Optional[int] = None, name: Optional[str] = None, ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -65,7 +62,6 @@ async def get_rarities(value: Optional[int] = None, name: Optional[str] = None, for x in all_rarities: return_val['rarities'].append(model_to_dict(x)) - db.close() return return_val @@ -74,7 +70,6 @@ async def get_one_rarity(rarity_id, csv: Optional[bool] = False): try: this_rarity = Rarity.get_by_id(rarity_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No rarity found with id {rarity_id}') if csv: @@ -87,11 +82,9 @@ async def get_one_rarity(rarity_id, csv: Optional[bool] = False): ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_rarity) - db.close() return return_val @@ -99,7 +92,6 @@ async def get_one_rarity(rarity_id, csv: Optional[bool] = False): async def post_rarity(rarity: RarityModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post rarities. This event has been logged.' @@ -107,7 +99,6 @@ async def post_rarity(rarity: RarityModel, token: str = Depends(oauth2_scheme)): dupe_team = Rarity.get_or_none(Rarity.name) if dupe_team: - db.close() raise HTTPException(status_code=400, detail=f'There is already a rarity using {rarity.name}') this_rarity = Rarity( @@ -119,7 +110,6 @@ async def post_rarity(rarity: RarityModel, token: str = Depends(oauth2_scheme)): saved = this_rarity.save() if saved == 1: return_val = model_to_dict(this_rarity) - db.close() return return_val else: raise HTTPException( @@ -134,7 +124,6 @@ async def patch_rarity( token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch rarities. This event has been logged.' @@ -142,7 +131,6 @@ async def patch_rarity( try: this_rarity = Rarity.get_by_id(rarity_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No rarity found with id {rarity_id}') if value is not None: @@ -154,7 +142,6 @@ async def patch_rarity( if this_rarity.save() == 1: return_val = model_to_dict(this_rarity) - db.close() return return_val else: raise HTTPException( @@ -167,7 +154,6 @@ async def patch_rarity( async def v1_rarities_delete(rarity_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete rarities. This event has been logged.' @@ -175,11 +161,9 @@ async def v1_rarities_delete(rarity_id, token: str = Depends(oauth2_scheme)): try: this_rarity = Rarity.get_by_id(rarity_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No rarity found with id {rarity_id}') count = this_rarity.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Rarity {rarity_id} has been deleted') diff --git a/app/routers_v2/results.py b/app/routers_v2/results.py index d863f43..0d54cd3 100644 --- a/app/routers_v2/results.py +++ b/app/routers_v2/results.py @@ -56,7 +56,6 @@ 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: - db.close() raise HTTPException(status_code=404, detail=f'No team found with id {away_team_id}') if home_team_id is not None: @@ -64,7 +63,6 @@ async def get_results( this_team = Team.get_by_id(home_team_id) all_results = all_results.where(Result.home_team == this_team) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No team found with id {home_team_id}') if team_one_id is not None: @@ -72,7 +70,6 @@ async def get_results( this_team = Team.get_by_id(team_one_id) all_results = all_results.where((Result.home_team == this_team) | (Result.away_team == this_team)) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No team found with id {team_one_id}') if team_two_id is not None: @@ -80,7 +77,6 @@ async def get_results( this_team = Team.get_by_id(team_two_id) all_results = all_results.where((Result.home_team == this_team) | (Result.away_team == this_team)) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No team found with id {team_two_id}') if away_score_min is not None: @@ -153,7 +149,6 @@ async def get_results( ]) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -161,7 +156,6 @@ async def get_results( for x in all_results: return_val['results'].append(model_to_dict(x)) - db.close() return return_val @@ -170,7 +164,6 @@ async def get_one_results(result_id, csv: Optional[bool] = None): try: this_result = Result.get_by_id(result_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No result found with id {result_id}') if csv: @@ -184,12 +177,10 @@ async def get_one_results(result_id, csv: Optional[bool] = None): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_result) - db.close() return return_val @@ -243,7 +234,6 @@ async def get_team_results( ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -254,7 +244,6 @@ async def get_team_results( 'casual_wins': c_wins, 'casual_losses': c_loss, } - db.close() return return_val @@ -262,7 +251,6 @@ async def get_team_results( async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post results. This event has been logged.' @@ -273,12 +261,10 @@ async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)): if result.ranked: if not result.away_team_ranking: - db.close() 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: - db.close() error = f'Ranked game did not include home team ({result.home_team_id}) ranking.' logging.error(error) raise DataError(error) @@ -328,10 +314,8 @@ async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)): if saved == 1: return_val = model_to_dict(this_result) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail='Well slap my ass and call me a teapot; I could not save that roster' @@ -347,7 +331,6 @@ async def patch_result( token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch results. This event has been logged.' @@ -355,7 +338,6 @@ async def patch_result( try: this_result = Result.get_by_id(result_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No result found with id {result_id}') if away_team_id is not None: @@ -396,10 +378,8 @@ async def patch_result( if this_result.save() == 1: return_val = model_to_dict(this_result) - db.close() return return_val else: - db.close() raise HTTPException( status_code=418, detail='Well slap my ass and call me a teapot; I could not save that event' @@ -410,7 +390,6 @@ async def patch_result( async def delete_result(result_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post results. This event has been logged.' @@ -418,11 +397,9 @@ async def delete_result(result_id, token: str = Depends(oauth2_scheme)): try: this_result = Result.get_by_id(result_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No result found with id {result_id}') count = this_result.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Result {result_id} has been deleted') diff --git a/app/routers_v2/rewards.py b/app/routers_v2/rewards.py index 4f79e63..81395b1 100644 --- a/app/routers_v2/rewards.py +++ b/app/routers_v2/rewards.py @@ -36,7 +36,6 @@ async def get_rewards( all_rewards = Reward.select().order_by(Reward.id) if all_rewards.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f'There are no rewards to filter') if name is not None: @@ -55,7 +54,6 @@ async def get_rewards( all_rewards = all_rewards.where(Reward.week == week) if all_rewards.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f'No rewards found') if csv: @@ -68,7 +66,6 @@ async def get_rewards( ) return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: @@ -76,7 +73,6 @@ async def get_rewards( for x in all_rewards: return_val['rewards'].append(model_to_dict(x, recurse=not flat)) - db.close() return return_val @@ -85,7 +81,6 @@ async def get_one_reward(reward_id, csv: Optional[bool] = False): try: this_reward = Reward.get_by_id(reward_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No reward found with id {reward_id}') if csv: @@ -95,12 +90,10 @@ async def get_one_reward(reward_id, csv: Optional[bool] = False): ] return_val = DataFrame(data_list).to_csv(header=False, index=False) - db.close() return Response(content=return_val, media_type='text/csv') else: return_val = model_to_dict(this_reward) - db.close() return return_val @@ -108,7 +101,6 @@ async def get_one_reward(reward_id, csv: Optional[bool] = False): async def post_rewards(reward: RewardModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to post rewards. This event has been logged.' @@ -123,7 +115,6 @@ async def post_rewards(reward: RewardModel, token: str = Depends(oauth2_scheme)) saved = this_reward.save() if saved == 1: return_val = model_to_dict(this_reward) - db.close() return return_val else: raise HTTPException( @@ -138,7 +129,6 @@ async def patch_reward( token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to patch rewards. This event has been logged.' @@ -146,7 +136,6 @@ async def patch_reward( try: this_reward = Reward.get_by_id(reward_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No reward found with id {reward_id}') if name is not None: @@ -159,7 +148,6 @@ async def patch_reward( if this_reward.save() == 1: return_val = model_to_dict(this_reward) - db.close() return return_val else: raise HTTPException( @@ -172,7 +160,6 @@ async def patch_reward( async def delete_reward(reward_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to delete rewards. This event has been logged.' @@ -180,11 +167,9 @@ async def delete_reward(reward_id, token: str = Depends(oauth2_scheme)): try: this_reward = Reward.get_by_id(reward_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f'No reward found with id {reward_id}') count = this_reward.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f'Reward {reward_id} has been deleted') diff --git a/app/routers_v2/scouting.py b/app/routers_v2/scouting.py index b412ae6..78464f4 100644 --- a/app/routers_v2/scouting.py +++ b/app/routers_v2/scouting.py @@ -50,7 +50,6 @@ async def get_player_keys(player_id: list = Query(default=None)): return_val = {'count': len(all_keys), 'keys': [ dict(x) for x in all_keys ]} - db.close() return return_val @@ -58,7 +57,6 @@ async def get_player_keys(player_id: list = Query(default=None)): def live_update_batting(files: BattingFiles, cardset_id: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to initiate live updates.' @@ -93,7 +91,6 @@ def live_update_batting(files: BattingFiles, cardset_id: int, token: str = Depen def live_update_pitching(files: BattingFiles, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'Bad Token: {token}') - db.close() raise HTTPException( status_code=401, detail='You are not authorized to initiate live updates.' diff --git a/app/routers_v2/stratgame.py b/app/routers_v2/stratgame.py index 9843df2..c2b7ac2 100644 --- a/app/routers_v2/stratgame.py +++ b/app/routers_v2/stratgame.py @@ -83,7 +83,6 @@ async def get_games( x['home_abbrev'] = x['home_team']['abbrev'] del x['away_team'], x['home_team'] - db.close() output = pd.DataFrame(return_vals)[[ 'id', 'away_abbrev', 'home_abbrev', 'away_score', 'home_score', 'away_team_value', 'home_team_value', 'game_type', 'season', 'week', 'short_game', 'ranked' @@ -94,7 +93,6 @@ async def get_games( return_val = {'count': all_games.count(), 'games': [ model_to_dict(x, recurse=not short_output) for x in all_games ]} - db.close() return return_val @@ -102,11 +100,9 @@ async def get_games( async def get_one_game(game_id: int): this_game = StratGame.get_or_none(StratGame.id == game_id) if not this_game: - db.close() raise HTTPException(status_code=404, detail=f'StratGame ID {game_id} not found') g_result = model_to_dict(this_game) - db.close() return g_result @@ -120,7 +116,6 @@ async def patch_game( this_game = StratGame.get_or_none(StratGame.id == game_id) if not this_game: - db.close() raise HTTPException(status_code=404, detail=f'StratGame ID {game_id} not found') if away_score is not None: @@ -132,10 +127,8 @@ async def patch_game( if this_game.save() == 1: g_result = model_to_dict(this_game) - db.close() return g_result else: - db.close() raise HTTPException(status_code=500, detail=f'Unable to patch game {game_id}') @@ -150,7 +143,6 @@ async def post_game(this_game: GameModel, token: str = Depends(oauth2_scheme)): saved = this_game.save() if saved == 1: return_val = model_to_dict(this_game) - db.close() return return_val else: raise HTTPException( @@ -167,11 +159,9 @@ async def delete_game(game_id: int, token: str = Depends(oauth2_scheme)): this_game = StratGame.get_or_none(StratGame.id == game_id) if not this_game: - db.close() raise HTTPException(status_code=404, detail=f'StratGame ID {game_id} not found') count = this_game.delete_instance() - db.close() if count == 1: return f'StratGame {game_id} has been deleted' diff --git a/app/routers_v2/stratplays.py b/app/routers_v2/stratplays.py index 95aecb2..0b15eee 100644 --- a/app/routers_v2/stratplays.py +++ b/app/routers_v2/stratplays.py @@ -367,7 +367,6 @@ async def get_plays( x["runner_team"], ) - db.close() return Response( content=pd.DataFrame(return_vals).to_csv(index=False), media_type="text/csv" ) @@ -376,7 +375,6 @@ async def get_plays( "count": all_plays.count(), "plays": [model_to_dict(x, recurse=not short_output) for x in all_plays], } - db.close() return return_plays @@ -808,12 +806,10 @@ async def get_batting_totals( exclude = first + ["lob_all", "lob_all_rate", "lob_2outs", "rbi%"] output = output[first + [col for col in output.columns if col not in exclude]] - db.close() return Response( content=pd.DataFrame(output).to_csv(index=False), media_type="text/csv" ) - db.close() return return_stats @@ -1175,7 +1171,6 @@ async def get_pitching_totals( "rbi%": rbi_rate, } ) - db.close() if csv: return_vals = return_stats["stats"] @@ -1209,7 +1204,6 @@ async def get_pitching_totals( exclude = first + ["lob_2outs", "rbi%"] output = output[first + [col for col in output.columns if col not in exclude]] - db.close() return Response( content=pd.DataFrame(output).to_csv(index=False), media_type="text/csv" ) @@ -1227,7 +1221,6 @@ async def get_game_summary( ): this_game = StratGame.get_or_none(StratGame.id == game_id) if this_game is None: - db.close() raise HTTPException(status_code=404, detail=f"Game {game_id} not found") game_plays = StratPlay.select().where(StratPlay.game_id == game_id) @@ -1405,10 +1398,8 @@ async def get_game_summary( @router.get("/{play_id}") async def get_one_play(play_id: int): if StratPlay.get_or_none(StratPlay.id == play_id) is None: - db.close() raise HTTPException(status_code=404, detail=f"Play ID {play_id} not found") r_play = model_to_dict(StratPlay.get_by_id(play_id)) - db.close() return r_play @@ -1421,12 +1412,10 @@ async def patch_play( raise HTTPException(status_code=401, detail="Unauthorized") if StratPlay.get_or_none(StratPlay.id == play_id) is None: - db.close() raise HTTPException(status_code=404, detail=f"Play ID {play_id} not found") StratPlay.update(**new_play.dict()).where(StratPlay.id == play_id).execute() r_play = model_to_dict(StratPlay.get_by_id(play_id)) - db.close() return r_play @@ -1476,7 +1465,6 @@ async def post_plays(p_list: PlayList, token: str = Depends(oauth2_scheme)): with db.atomic(): # Use PostgreSQL-compatible upsert helper upsert_strat_plays(new_plays, batch_size=20) - db.close() return f"Inserted {len(new_plays)} plays" @@ -1489,11 +1477,9 @@ async def delete_play(play_id: int, token: str = Depends(oauth2_scheme)): this_play = StratPlay.get_or_none(StratPlay.id == play_id) if not this_play: - db.close() raise HTTPException(status_code=404, detail=f"Play ID {play_id} not found") count = this_play.delete_instance() - db.close() if count == 1: return f"Play {play_id} has been deleted" @@ -1511,11 +1497,9 @@ async def delete_plays_game(game_id: int, token: str = Depends(oauth2_scheme)): this_game = StratGame.get_or_none(StratGame.id == game_id) if not this_game: - db.close() raise HTTPException(status_code=404, detail=f"Game ID {game_id} not found") count = StratPlay.delete().where(StratPlay.game == this_game).execute() - db.close() if count > 0: return f"Deleted {count} plays matching Game ID {game_id}" diff --git a/app/routers_v2/teams.py b/app/routers_v2/teams.py index 696daf6..17a4eee 100644 --- a/app/routers_v2/teams.py +++ b/app/routers_v2/teams.py @@ -163,7 +163,6 @@ async def get_teams( if csv: return_val = query_to_csv(all_teams, exclude=[Team.career]) - db.close() return Response(content=return_val, media_type="text/csv") else: @@ -171,7 +170,6 @@ async def get_teams( for x in all_teams: return_teams["teams"].append(model_to_dict(x)) - db.close() return return_teams @@ -180,7 +178,6 @@ async def get_one_team(team_id, inc_packs: bool = True, csv: Optional[bool] = Fa try: this_team = Team.get_by_id(team_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f"No team found with id {team_id}") p_query = Pack.select().where( @@ -195,7 +192,6 @@ async def get_one_team(team_id, inc_packs: bool = True, csv: Optional[bool] = Fa if inc_packs: return_val["sealed_packs"] = [model_to_dict(x) for x in p_query] - db.close() return return_val @@ -284,7 +280,6 @@ def get_scouting_dfs(allowed_players, position: str): ) ) - db.close() def get_total_ops(df_data): ops_vl = df_data["obp_vl"] + df_data["slg_vl"] @@ -311,11 +306,9 @@ async def get_team_lineup( """ this_team = Team.get_or_none(Team.id == team_id) if this_team is None: - db.close() raise HTTPException(status_code=404, detail=f"Team id {team_id} not found") if difficulty_name not in CARDSETS.keys() and difficulty_name != "exhibition": - db.close() raise HTTPException( status_code=400, detail=f"Difficulty name {difficulty_name} not a valid check", @@ -329,7 +322,6 @@ async def get_team_lineup( if difficulty_name == "exhibition": logging.info(f"pulling an exhibition lineup") if cardset_id is None: - db.close() raise HTTPException( status_code=400, detail=f"Must provide at least one cardset_id for exhibition lineups", @@ -628,11 +620,9 @@ async def get_team_sp( ) this_team = Team.get_or_none(Team.id == team_id) if this_team is None: - db.close() raise HTTPException(status_code=404, detail=f"Team id {team_id} not found") if difficulty_name not in CARDSETS.keys() and difficulty_name != "exhibition": - db.close() raise HTTPException( status_code=400, detail=f"Difficulty name {difficulty_name} not a valid check", @@ -643,7 +633,6 @@ async def get_team_sp( if difficulty_name == "exhibition": logging.info(f"pulling an exhibition lineup") if cardset_id is None: - db.close() raise HTTPException( status_code=400, detail=f"Must provide at least one cardset_id for exhibition lineups", @@ -707,13 +696,11 @@ async def get_team_sp( if all_starters is not None and len(all_starters.index) >= sp_rank: this_player_id = all_starters.iloc[sp_rank - 1].player this_player = model_to_dict(Player.get_by_id(this_player_id), recurse=False) - db.close() return this_player if all_starters is not None and len(all_starters.index) > 0: this_player_id = all_starters.iloc[len(all_starters.index) - 1].player this_player = model_to_dict(Player.get_by_id(this_player_id), recurse=False) - db.close() return this_player # Include backup cardsets @@ -726,13 +713,11 @@ async def get_team_sp( if all_starters is not None and len(all_starters.index) >= sp_rank: this_player_id = all_starters.iloc[sp_rank - 1].player this_player = model_to_dict(Player.get_by_id(this_player_id), recurse=False) - db.close() return this_player if all_starters is not None and len(all_starters.index) > 0: this_player_id = all_starters.iloc[len(all_starters.index) - 1].player this_player = model_to_dict(Player.get_by_id(this_player_id), recurse=False) - db.close() return this_player raise HTTPException( @@ -755,11 +740,9 @@ async def get_team_rp( ) this_team = Team.get_or_none(Team.id == team_id) if this_team is None: - db.close() raise HTTPException(status_code=404, detail=f"Team id {team_id} not found") if difficulty_name not in CARDSETS.keys() and difficulty_name != "exhibition": - db.close() raise HTTPException( status_code=400, detail=f"Difficulty name {difficulty_name} not a valid check", @@ -773,7 +756,6 @@ async def get_team_rp( if difficulty_name == "exhibition": logging.info(f"pulling an exhibition RP") if cardset_id is None: - db.close() raise HTTPException( status_code=400, detail=f"Must provide at least one cardset_id for exhibition lineups", @@ -845,7 +827,6 @@ async def get_team_rp( this_player = model_to_dict( Player.get_by_id(this_player_id), recurse=False ) - db.close() return this_player elif need == "setup": @@ -870,7 +851,6 @@ async def get_team_rp( this_player = model_to_dict( Player.get_by_id(this_player_id), recurse=False ) - db.close() return this_player elif need == "length" or len(used_pitcher_ids) > 4: @@ -904,7 +884,6 @@ async def get_team_rp( this_player = model_to_dict( Player.get_by_id(this_player_id), recurse=False ) - db.close() return this_player elif need == "middle": @@ -929,7 +908,6 @@ async def get_team_rp( this_player = model_to_dict( Player.get_by_id(this_player_id), recurse=False ) - db.close() return this_player logging.info(f"Falling to last chance pitcher") @@ -945,7 +923,6 @@ async def get_team_rp( if all_relievers is not None: this_player_id = all_relievers.iloc[len(all_relievers.index) - 1].player this_player = model_to_dict(Player.get_by_id(this_player_id), recurse=False) - db.close() return this_player raise HTTPException(status_code=400, detail=f"No RP found for Team {team_id}") @@ -1031,7 +1008,6 @@ async def get_team_record(team_id: int, season: int): # team_games = lg_query.where((StratGame.away_team_id == x) | (StratGame.home_team_id == x)) # for game in team_games: - db.close() return standings @@ -1040,12 +1016,10 @@ async def team_buy_players(team_id: int, ids: str, ts: str): try: this_team = Team.get_by_id(team_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f"No team found with id {team_id}") if ts != this_team.team_hash(): logging.warning(f"Bad Team Secret: {ts} ({this_team.team_hash()})") - db.close() raise HTTPException( status_code=401, detail=f"You are not authorized to buy {this_team.abbrev} cards. This event has been logged.", @@ -1062,7 +1036,6 @@ async def team_buy_players(team_id: int, ids: str, ts: str): try: this_player = Player.get_by_id(player_id) except Exception: - db.close() raise HTTPException( status_code=404, detail=f"No player found with id {player_id} /// " @@ -1075,7 +1048,6 @@ async def team_buy_players(team_id: int, ids: str, ts: str): f"{this_player} was not purchased. {this_team.lname} only has {this_team.wallet}₼, but " f"{this_player} costs {this_player.cost}₼." ) - db.close() raise HTTPException( 200, detail=f"{this_player} was not purchased. {this_team.lname} only has {this_team.wallet}₼, but " @@ -1132,7 +1104,6 @@ async def team_buy_packs( try: this_packtype = PackType.get_by_id(packtype_id) except Exception: - db.close() raise HTTPException( status_code=404, detail=f"No pack type found with id {packtype_id}" ) @@ -1140,12 +1111,10 @@ async def team_buy_packs( try: this_team = Team.get_by_id(team_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f"No team found with id {team_id}") if ts != this_team.team_hash(): logging.warning(f"Bad Team Secret: {ts} ({this_team.team_hash()})") - db.close() logging.warning( f"team: {this_team} / pack_type: {this_packtype} / secret: {ts} / " f"actual: {this_team.team_hash()}" @@ -1158,7 +1127,6 @@ async def team_buy_packs( # check wallet balance total_cost = this_packtype.cost * quantity if this_team.wallet < total_cost: - db.close() raise HTTPException( 200, detail=f"{this_packtype} was not purchased. {this_team.lname} only has {this_team.wallet} bucks, but " @@ -1186,7 +1154,6 @@ async def team_buy_packs( with db.atomic(): Pack.bulk_create(all_packs, batch_size=15) - db.close() raise HTTPException( status_code=200, @@ -1200,12 +1167,10 @@ async def team_sell_cards(team_id: int, ids: str, ts: str): try: this_team = Team.get_by_id(team_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f"No team found with id {team_id}") if ts != this_team.team_hash(): logging.warning(f"Bad Team Secret: {ts} ({this_team.team_hash()})") - db.close() raise HTTPException( status_code=401, detail=f"You are not authorized to sell {this_team.abbrev} cards. This event has been logged.", @@ -1220,7 +1185,6 @@ async def team_sell_cards(team_id: int, ids: str, ts: str): try: this_card = Card.get_by_id(card_id) except Exception: - db.close() raise HTTPException( status_code=404, detail=f"No card found with id {card_id}" ) @@ -1289,11 +1253,9 @@ async def get_team_cards(team_id, csv: Optional[bool] = True): try: this_team = Team.get_by_id(team_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f"No team found with id {team_id}") if not csv: - db.close() raise HTTPException( status_code=400, detail="The /teams/{team_id}/cards endpoint only supports csv output.", @@ -1307,11 +1269,9 @@ async def get_team_cards(team_id, csv: Optional[bool] = True): .order_by(-Card.player.rarity.value, Card.player.p_name) ) if all_cards.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f"No cards found") card_vals = [model_to_dict(x) for x in all_cards] - db.close() for x in card_vals: x.update(x["player"]) @@ -1356,7 +1316,6 @@ async def get_team_cards(team_id, csv: Optional[bool] = True): async def post_team(team: TeamModel, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post teams. This event has been logged.", @@ -1364,7 +1323,6 @@ async def post_team(team: TeamModel, token: str = Depends(oauth2_scheme)): dupe_team = Team.get_or_none(Team.season == team.season, Team.abbrev == team.abbrev) if dupe_team: - db.close() raise HTTPException( status_code=400, detail=f"There is already a season {team.season} team using {team.abbrev}", @@ -1392,7 +1350,6 @@ async def post_team(team: TeamModel, token: str = Depends(oauth2_scheme)): saved = this_team.save() if saved == 1: return_team = model_to_dict(this_team) - db.close() return return_team else: raise HTTPException( @@ -1405,7 +1362,6 @@ async def post_team(team: TeamModel, token: str = Depends(oauth2_scheme)): async def team_season_update(new_season: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to post teams. This event has been logged.", @@ -1417,7 +1373,6 @@ async def team_season_update(new_season: int, token: str = Depends(oauth2_scheme current = Current.latest() current.season = new_season current.save() - db.close() return { "detail": f"Team rankings, season, guides, and wallets updated for season {new_season}" @@ -1430,7 +1385,6 @@ async def team_update_money( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to adjust wallets. This event has been logged.", @@ -1439,14 +1393,12 @@ async def team_update_money( try: this_team = Team.get_by_id(team_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f"No team found with id {team_id}") this_team.wallet += delta if this_team.save() == 1: return_team = model_to_dict(this_team) - db.close() return return_team else: raise HTTPException( @@ -1478,7 +1430,6 @@ async def patch_team( ): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to delete teams. This event has been logged.", @@ -1486,7 +1437,6 @@ async def patch_team( try: this_team = Team.get_by_id(team_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f"No team found with id {team_id}") if abbrev is not None: @@ -1530,7 +1480,6 @@ async def patch_team( if this_team.save() == 1: return_team = model_to_dict(this_team) - db.close() return return_team else: raise HTTPException( @@ -1543,7 +1492,6 @@ async def patch_team( async def delete_team(team_id, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f"Bad Token: {token}") - db.close() raise HTTPException( status_code=401, detail="You are not authorized to delete teams. This event has been logged.", @@ -1551,11 +1499,9 @@ async def delete_team(team_id, token: str = Depends(oauth2_scheme)): try: this_team = Team.get_by_id(team_id) except Exception: - db.close() raise HTTPException(status_code=404, detail=f"No team found with id {team_id}") count = this_team.delete_instance() - db.close() if count == 1: raise HTTPException(status_code=200, detail=f"Team {team_id} has been deleted")