diff --git a/app/main.py b/app/main.py index 2a8bbff..58a5ffe 100644 --- a/app/main.py +++ b/app/main.py @@ -71,6 +71,19 @@ app = FastAPI( logger.info(f"Starting up now...") +@app.middleware("http") +async def db_connection_middleware(request: Request, call_next): + from .db_engine import db + + db.connect(reuse_if_open=True) + try: + response = await call_next(request) + return response + finally: + if not db.is_closed(): + db.close() + + @app.middleware("http") async def strip_empty_query_params(request: Request, call_next): qs = request.scope.get("query_string", b"") diff --git a/app/routers_v3/awards.py b/app/routers_v3/awards.py index 01583ab..fe1d3f4 100644 --- a/app/routers_v3/awards.py +++ b/app/routers_v3/awards.py @@ -78,7 +78,6 @@ async def get_awards( "count": total_count, "awards": [model_to_dict(x, recurse=not short_output) for x in all_awards], } - db.close() return return_awards @@ -87,10 +86,8 @@ async def get_awards( async def get_one_award(award_id: int, short_output: Optional[bool] = False): this_award = Award.get_or_none(Award.id == award_id) if this_award is None: - db.close() raise HTTPException(status_code=404, detail=f"Award ID {award_id} not found") - db.close() return model_to_dict(this_award, recurse=not short_output) @@ -114,7 +111,6 @@ async def patch_award( this_award = Award.get_or_none(Award.id == award_id) if this_award is None: - db.close() raise HTTPException(status_code=404, detail=f"Award ID {award_id} not found") if name is not None: @@ -136,10 +132,8 @@ async def patch_award( if this_award.save() == 1: r_award = model_to_dict(this_award) - db.close() return r_award else: - db.close() raise HTTPException(status_code=500, detail=f"Unable to patch award {award_id}") @@ -183,7 +177,6 @@ async def post_award(award_list: AwardList, token: str = Depends(oauth2_scheme)) with db.atomic(): for batch in chunked(new_awards, 15): Award.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_awards)} awards" @@ -197,11 +190,9 @@ async def delete_award(award_id: int, token: str = Depends(oauth2_scheme)): this_award = Award.get_or_none(Award.id == award_id) if this_award is None: - db.close() raise HTTPException(status_code=404, detail=f"Award ID {award_id} not found") count = this_award.delete_instance() - db.close() if count == 1: return f"Award {award_id} has been deleted" diff --git a/app/routers_v3/battingstats.py b/app/routers_v3/battingstats.py index 11bd14d..df88a3f 100644 --- a/app/routers_v3/battingstats.py +++ b/app/routers_v3/battingstats.py @@ -93,17 +93,14 @@ async def get_batstats( if "post" in s_type.lower(): all_stats = BattingStat.post_season(season) if all_stats.count() == 0: - db.close() return {"count": 0, "stats": []} elif s_type.lower() in ["combined", "total", "all"]: all_stats = BattingStat.combined_season(season) if all_stats.count() == 0: - db.close() return {"count": 0, "stats": []} else: all_stats = BattingStat.regular_season(season) if all_stats.count() == 0: - db.close() return {"count": 0, "stats": []} if position is not None: @@ -129,7 +126,6 @@ async def get_batstats( if week_end is not None: end = min(week_end, end) if start > end: - db.close() raise HTTPException( status_code=404, detail=f"Start week {start} is after end week {end} - cannot pull stats", @@ -147,7 +143,6 @@ async def get_batstats( # 'stats': [{'id': x.id} for x in all_stats] } - db.close() return return_stats @@ -350,7 +345,6 @@ async def get_totalstats( "bplo": x.sum_bplo, } ) - db.close() return return_stats @@ -374,7 +368,6 @@ async def patch_batstats( BattingStat.update(**new_stats.dict()).where(BattingStat.id == stat_id).execute() r_stat = model_to_dict(BattingStat.get_by_id(stat_id)) - db.close() return r_stat @@ -418,5 +411,4 @@ async def post_batstats(s_list: BatStatList, token: str = Depends(oauth2_scheme) # Update career stats - db.close() return f"Added {len(all_stats)} batting lines" diff --git a/app/routers_v3/current.py b/app/routers_v3/current.py index ba4458f..889c38a 100644 --- a/app/routers_v3/current.py +++ b/app/routers_v3/current.py @@ -41,7 +41,6 @@ async def get_current(season: Optional[int] = None): if current is not None: r_curr = model_to_dict(current) - db.close() return r_curr else: return None @@ -100,10 +99,8 @@ async def patch_current( if current.save(): r_curr = model_to_dict(current) - db.close() return r_curr else: - db.close() raise HTTPException( status_code=500, detail=f"Unable to patch current {current_id}" ) @@ -120,10 +117,8 @@ async def post_current(new_current: CurrentModel, token: str = Depends(oauth2_sc if this_current.save(): r_curr = model_to_dict(this_current) - db.close() return r_curr else: - db.close() raise HTTPException( status_code=500, detail=f"Unable to post season {new_current.season} current", diff --git a/app/routers_v3/custom_commands.py b/app/routers_v3/custom_commands.py index 577e78d..56bc53b 100644 --- a/app/routers_v3/custom_commands.py +++ b/app/routers_v3/custom_commands.py @@ -363,8 +363,6 @@ async def get_custom_commands( except Exception as e: logger.error(f"Error getting custom commands: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() # Move this route to after the specific string routes @@ -429,8 +427,6 @@ async def create_custom_command_endpoint( except Exception as e: logger.error(f"Error creating custom command: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.put("/{command_id}", include_in_schema=PRIVATE_IN_SCHEMA) @@ -490,8 +486,6 @@ async def update_custom_command_endpoint( except Exception as e: logger.error(f"Error updating custom command {command_id}: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.patch("/{command_id}", include_in_schema=PRIVATE_IN_SCHEMA) @@ -575,8 +569,6 @@ async def patch_custom_command( except Exception as e: logger.error(f"Error patching custom command {command_id}: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.delete("/{command_id}", include_in_schema=PRIVATE_IN_SCHEMA) @@ -612,8 +604,6 @@ async def delete_custom_command_endpoint( except Exception as e: logger.error(f"Error deleting custom command {command_id}: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() # Creator endpoints @@ -683,8 +673,6 @@ async def get_creators( except Exception as e: logger.error(f"Error getting creators: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.post("/creators", include_in_schema=PRIVATE_IN_SCHEMA) @@ -728,8 +716,6 @@ async def create_creator_endpoint( except Exception as e: logger.error(f"Error creating creator: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.get("/stats") @@ -854,8 +840,6 @@ async def get_custom_command_stats(): except Exception as e: logger.error(f"Error getting custom command stats: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() # Special endpoints for Discord bot integration @@ -921,8 +905,6 @@ async def get_custom_command_by_name_endpoint(command_name: str): except Exception as e: logger.error(f"Error getting custom command by name '{command_name}': {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.patch("/by_name/{command_name}/execute", include_in_schema=PRIVATE_IN_SCHEMA) @@ -990,8 +972,6 @@ async def execute_custom_command( except Exception as e: logger.error(f"Error executing custom command '{command_name}': {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.get("/autocomplete") @@ -1027,8 +1007,6 @@ async def get_command_names_for_autocomplete( except Exception as e: logger.error(f"Error getting command names for autocomplete: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.get("/{command_id}") @@ -1077,5 +1055,3 @@ async def get_custom_command(command_id: int): except Exception as e: logger.error(f"Error getting custom command {command_id}: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() diff --git a/app/routers_v3/decisions.py b/app/routers_v3/decisions.py index 667a902..98b52c9 100644 --- a/app/routers_v3/decisions.py +++ b/app/routers_v3/decisions.py @@ -143,7 +143,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() return return_dec @@ -168,7 +167,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" ) @@ -194,10 +192,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}" ) @@ -226,7 +222,6 @@ async def post_decisions(dec_list: DecisionList, token: str = Depends(oauth2_sch with db.atomic(): for batch in chunked(new_dec, 10): Decision.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_dec)} decisions" @@ -240,13 +235,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" @@ -265,11 +258,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_v3/divisions.py b/app/routers_v3/divisions.py index 03888d3..39f721f 100644 --- a/app/routers_v3/divisions.py +++ b/app/routers_v3/divisions.py @@ -55,7 +55,6 @@ async def get_divisions( "count": total_count, "divisions": [model_to_dict(x) for x in all_divisions], } - db.close() return return_div @@ -64,13 +63,11 @@ async def get_divisions( async def get_one_division(division_id: int): this_div = Division.get_or_none(Division.id == division_id) if this_div is None: - db.close() raise HTTPException( status_code=404, detail=f"Division ID {division_id} not found" ) r_div = model_to_dict(this_div) - db.close() return r_div @@ -90,7 +87,6 @@ async def patch_division( this_div = Division.get_or_none(Division.id == division_id) if this_div is None: - db.close() raise HTTPException( status_code=404, detail=f"Division ID {division_id} not found" ) @@ -106,10 +102,8 @@ async def patch_division( if this_div.save() == 1: r_division = model_to_dict(this_div) - db.close() return r_division else: - db.close() raise HTTPException( status_code=500, detail=f"Unable to patch division {division_id}" ) @@ -128,10 +122,8 @@ async def post_division( if this_division.save() == 1: r_division = model_to_dict(this_division) - db.close() return r_division else: - db.close() raise HTTPException(status_code=500, detail=f"Unable to post division") @@ -144,13 +136,11 @@ async def delete_division(division_id: int, token: str = Depends(oauth2_scheme)) this_div = Division.get_or_none(Division.id == division_id) if this_div is None: - db.close() raise HTTPException( status_code=404, detail=f"Division ID {division_id} not found" ) count = this_div.delete_instance() - db.close() if count == 1: return f"Division {division_id} has been deleted" diff --git a/app/routers_v3/draftdata.py b/app/routers_v3/draftdata.py index 1329fb9..f7478c6 100644 --- a/app/routers_v3/draftdata.py +++ b/app/routers_v3/draftdata.py @@ -32,7 +32,6 @@ async def get_draftdata(): if draft_data is not None: r_data = model_to_dict(draft_data) - db.close() return r_data raise HTTPException(status_code=404, detail=f'No draft data found') @@ -50,7 +49,6 @@ async def patch_draftdata( draft_data = DraftData.get_or_none(DraftData.id == data_id) if draft_data is None: - db.close() raise HTTPException(status_code=404, detail=f'No draft data found') if currentpick is not None: @@ -68,7 +66,6 @@ async def patch_draftdata( saved = draft_data.save() r_data = model_to_dict(draft_data) - db.close() if saved == 1: return r_data diff --git a/app/routers_v3/draftlist.py b/app/routers_v3/draftlist.py index de3ae6e..8d544d7 100644 --- a/app/routers_v3/draftlist.py +++ b/app/routers_v3/draftlist.py @@ -55,7 +55,6 @@ async def get_draftlist( r_list = {"count": total_count, "picks": [model_to_dict(x) for x in all_list]} - db.close() return r_list @@ -76,7 +75,6 @@ async def get_team_draftlist(team_id: int, token: str = Depends(oauth2_scheme)): "picks": [model_to_dict(x) for x in this_list], } - db.close() return r_list @@ -106,7 +104,6 @@ async def post_draftlist( for batch in chunked(new_list, 15): DraftList.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_list)} list values" @@ -118,5 +115,4 @@ async def delete_draftlist(team_id: int, token: str = Depends(oauth2_scheme)): raise HTTPException(status_code=401, detail="Unauthorized") count = DraftList.delete().where(DraftList.team_id == team_id).execute() - db.close() return f"Deleted {count} list values" diff --git a/app/routers_v3/draftpicks.py b/app/routers_v3/draftpicks.py index a2dba4e..3524404 100644 --- a/app/routers_v3/draftpicks.py +++ b/app/routers_v3/draftpicks.py @@ -124,7 +124,6 @@ async def get_picks( for line in all_picks: return_picks["picks"].append(model_to_dict(line, recurse=not short_output)) - db.close() return return_picks @@ -136,7 +135,6 @@ async def get_one_pick(pick_id: int, short_output: Optional[bool] = False): r_pick = model_to_dict(this_pick, recurse=not short_output) else: raise HTTPException(status_code=404, detail=f"Pick ID {pick_id} not found") - db.close() return r_pick @@ -154,7 +152,6 @@ async def patch_pick( DraftPick.update(**new_pick.dict()).where(DraftPick.id == pick_id).execute() r_pick = model_to_dict(DraftPick.get_by_id(pick_id)) - db.close() return r_pick @@ -171,7 +168,6 @@ async def post_picks(p_list: DraftPickList, token: str = Depends(oauth2_scheme)) DraftPick.season == pick.season, DraftPick.overall == pick.overall ) if dupe: - db.close() raise HTTPException( status_code=500, detail=f"Pick # {pick.overall} already exists for season {pick.season}", @@ -182,7 +178,6 @@ async def post_picks(p_list: DraftPickList, token: str = Depends(oauth2_scheme)) with db.atomic(): for batch in chunked(new_picks, 15): DraftPick.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_picks)} picks" @@ -199,7 +194,6 @@ async def delete_pick(pick_id: int, token: str = Depends(oauth2_scheme)): raise HTTPException(status_code=404, detail=f"Pick ID {pick_id} not found") count = this_pick.delete_instance() - db.close() if count == 1: return f"Draft pick {pick_id} has been deleted" diff --git a/app/routers_v3/fieldingstats.py b/app/routers_v3/fieldingstats.py index e892eab..4c5de82 100644 --- a/app/routers_v3/fieldingstats.py +++ b/app/routers_v3/fieldingstats.py @@ -46,17 +46,14 @@ async def get_fieldingstats( if "post" in s_type.lower(): all_stats = BattingStat.post_season(season) if all_stats.count() == 0: - db.close() return {"count": 0, "stats": []} elif s_type.lower() in ["combined", "total", "all"]: all_stats = BattingStat.combined_season(season) if all_stats.count() == 0: - db.close() return {"count": 0, "stats": []} else: all_stats = BattingStat.regular_season(season) if all_stats.count() == 0: - db.close() return {"count": 0, "stats": []} all_stats = all_stats.where( @@ -86,7 +83,6 @@ async def get_fieldingstats( if week_end is not None: end = min(week_end, end) if start > end: - db.close() raise HTTPException( status_code=404, detail=f"Start week {start} is after end week {end} - cannot pull stats", @@ -124,7 +120,6 @@ async def get_fieldingstats( ], } - db.close() return return_stats @@ -282,5 +277,4 @@ async def get_totalstats( ) return_stats["count"] = len(return_stats["stats"]) - db.close() return return_stats diff --git a/app/routers_v3/help_commands.py b/app/routers_v3/help_commands.py index 6d757c7..5b6df18 100644 --- a/app/routers_v3/help_commands.py +++ b/app/routers_v3/help_commands.py @@ -138,8 +138,6 @@ async def get_help_commands( except Exception as e: logger.error(f"Error getting help commands: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.post("/", include_in_schema=PRIVATE_IN_SCHEMA) @@ -187,8 +185,6 @@ async def create_help_command_endpoint( except Exception as e: logger.error(f"Error creating help command: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.put("/{command_id}", include_in_schema=PRIVATE_IN_SCHEMA) @@ -238,8 +234,6 @@ async def update_help_command_endpoint( except Exception as e: logger.error(f"Error updating help command {command_id}: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.patch("/{command_id}/restore", include_in_schema=PRIVATE_IN_SCHEMA) @@ -277,8 +271,6 @@ async def restore_help_command_endpoint( except Exception as e: logger.error(f"Error restoring help command {command_id}: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.delete("/{command_id}", include_in_schema=PRIVATE_IN_SCHEMA) @@ -309,8 +301,6 @@ async def delete_help_command_endpoint( except Exception as e: logger.error(f"Error deleting help command {command_id}: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.get("/stats") @@ -368,8 +358,6 @@ async def get_help_command_stats(): except Exception as e: logger.error(f"Error getting help command stats: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() # Special endpoints for Discord bot integration @@ -402,8 +390,6 @@ async def get_help_command_by_name_endpoint( except Exception as e: logger.error(f"Error getting help command by name '{command_name}': {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.patch("/by_name/{command_name}/view", include_in_schema=PRIVATE_IN_SCHEMA) @@ -439,8 +425,6 @@ async def increment_view_count(command_name: str, token: str = Depends(oauth2_sc except Exception as e: logger.error(f"Error incrementing view count for '{command_name}': {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.get("/autocomplete") @@ -470,8 +454,6 @@ async def get_help_names_for_autocomplete( except Exception as e: logger.error(f"Error getting help names for autocomplete: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() @router.get("/{command_id}") @@ -499,5 +481,3 @@ async def get_help_command(command_id: int): except Exception as e: logger.error(f"Error getting help command {command_id}: {e}") raise HTTPException(status_code=500, detail=str(e)) - finally: - db.close() diff --git a/app/routers_v3/injuries.py b/app/routers_v3/injuries.py index e568878..730378c 100644 --- a/app/routers_v3/injuries.py +++ b/app/routers_v3/injuries.py @@ -75,7 +75,6 @@ async def get_injuries( "count": total_count, "injuries": [model_to_dict(x, recurse=not short_output) for x in all_injuries], } - db.close() return return_injuries @@ -92,7 +91,6 @@ async def patch_injury( this_injury = Injury.get_or_none(Injury.id == injury_id) if this_injury is None: - db.close() raise HTTPException(status_code=404, detail=f"Injury ID {injury_id} not found") if is_active is not None: @@ -100,10 +98,8 @@ async def patch_injury( if this_injury.save() == 1: r_injury = model_to_dict(this_injury) - db.close() return r_injury else: - db.close() raise HTTPException( status_code=500, detail=f"Unable to patch injury {injury_id}" ) @@ -120,10 +116,8 @@ async def post_injury(new_injury: InjuryModel, token: str = Depends(oauth2_schem if this_injury.save(): r_injury = model_to_dict(this_injury) - db.close() return r_injury else: - db.close() raise HTTPException(status_code=500, detail=f"Unable to post injury") @@ -136,11 +130,9 @@ async def delete_injury(injury_id: int, token: str = Depends(oauth2_scheme)): this_injury = Injury.get_or_none(Injury.id == injury_id) if this_injury is None: - db.close() raise HTTPException(status_code=404, detail=f"Injury ID {injury_id} not found") count = this_injury.delete_instance() - db.close() if count == 1: return f"Injury {injury_id} has been deleted" diff --git a/app/routers_v3/keepers.py b/app/routers_v3/keepers.py index 36a8f26..ad8d4e7 100644 --- a/app/routers_v3/keepers.py +++ b/app/routers_v3/keepers.py @@ -55,7 +55,6 @@ async def get_keepers( "count": total_count, "keepers": [model_to_dict(x, recurse=not short_output) for x in all_keepers], } - db.close() return return_keepers @@ -85,10 +84,8 @@ async def patch_keeper( if this_keeper.save(): r_keeper = model_to_dict(this_keeper) - db.close() return r_keeper else: - db.close() raise HTTPException( status_code=500, detail=f"Unable to patch keeper {keeper_id}" ) @@ -108,7 +105,6 @@ async def post_keepers(k_list: KeeperList, token: str = Depends(oauth2_scheme)): with db.atomic(): for batch in chunked(new_keepers, 14): Keeper.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_keepers)} keepers" @@ -125,7 +121,6 @@ async def delete_keeper(keeper_id: int, token: str = Depends(oauth2_scheme)): raise HTTPException(status_code=404, detail=f"Keeper ID {keeper_id} not found") count = this_keeper.delete_instance() - db.close() if count == 1: return f"Keeper ID {keeper_id} has been deleted" diff --git a/app/routers_v3/managers.py b/app/routers_v3/managers.py index 2cd01c3..0e24c5f 100644 --- a/app/routers_v3/managers.py +++ b/app/routers_v3/managers.py @@ -84,7 +84,6 @@ async def get_managers( ], } - db.close() return return_managers @@ -94,7 +93,6 @@ async def get_one_manager(manager_id: int, short_output: Optional[bool] = False) this_manager = Manager.get_or_none(Manager.id == manager_id) if this_manager is not None: r_manager = model_to_dict(this_manager, recurse=not short_output) - db.close() return r_manager else: raise HTTPException(status_code=404, detail=f"Manager {manager_id} not found") @@ -116,7 +114,6 @@ async def patch_manager( this_manager = Manager.get_or_none(Manager.id == manager_id) if this_manager is None: - db.close() raise HTTPException( status_code=404, detail=f"Manager ID {manager_id} not found" ) @@ -132,10 +129,8 @@ async def patch_manager( if this_manager.save() == 1: r_manager = model_to_dict(this_manager) - db.close() return r_manager else: - db.close() raise HTTPException( status_code=500, detail=f"Unable to patch manager {this_manager}" ) @@ -152,10 +147,8 @@ async def post_manager(new_manager: ManagerModel, token: str = Depends(oauth2_sc if this_manager.save(): r_manager = model_to_dict(this_manager) - db.close() return r_manager else: - db.close() raise HTTPException( status_code=500, detail=f"Unable to post manager {this_manager.name}" ) @@ -170,13 +163,11 @@ async def delete_manager(manager_id: int, token: str = Depends(oauth2_scheme)): this_manager = Manager.get_or_none(Manager.id == manager_id) if this_manager is None: - db.close() raise HTTPException( status_code=404, detail=f"Manager ID {manager_id} not found" ) count = this_manager.delete_instance() - db.close() if count == 1: return f"Manager {manager_id} has been deleted" diff --git a/app/routers_v3/pitchingstats.py b/app/routers_v3/pitchingstats.py index f9073f8..a61003a 100644 --- a/app/routers_v3/pitchingstats.py +++ b/app/routers_v3/pitchingstats.py @@ -78,17 +78,14 @@ async def get_pitstats( if "post" in s_type.lower(): all_stats = PitchingStat.post_season(season) if all_stats.count() == 0: - db.close() return {"count": 0, "stats": []} elif s_type.lower() in ["combined", "total", "all"]: all_stats = PitchingStat.combined_season(season) if all_stats.count() == 0: - db.close() return {"count": 0, "stats": []} else: all_stats = PitchingStat.regular_season(season) if all_stats.count() == 0: - db.close() return {"count": 0, "stats": []} if team_abbrev is not None: @@ -114,7 +111,6 @@ async def get_pitstats( if week_end is not None: end = min(week_end, end) if start > end: - db.close() raise HTTPException( status_code=404, detail=f"Start week {start} is after end week {end} - cannot pull stats", @@ -133,7 +129,6 @@ async def get_pitstats( "stats": [model_to_dict(x, recurse=not short_output) for x in all_stats], } - db.close() return return_stats @@ -307,7 +302,6 @@ async def get_totalstats( "bsv": x.sum_bsv, } ) - db.close() return return_stats @@ -325,7 +319,6 @@ async def patch_pitstats( PitchingStat.update(**new_stats.dict()).where(PitchingStat.id == stat_id).execute() r_stat = model_to_dict(PitchingStat.get_by_id(stat_id)) - db.close() return r_stat @@ -356,5 +349,4 @@ async def post_pitstats(s_list: PitStatList, token: str = Depends(oauth2_scheme) for batch in chunked(all_stats, 15): PitchingStat.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Added {len(all_stats)} batting lines" diff --git a/app/routers_v3/results.py b/app/routers_v3/results.py index f8936e8..8b7298b 100644 --- a/app/routers_v3/results.py +++ b/app/routers_v3/results.py @@ -85,7 +85,6 @@ async def get_results( "count": total_count, "results": [model_to_dict(x, recurse=not short_output) for x in all_results], } - db.close() return return_results @@ -97,7 +96,6 @@ async def get_one_result(result_id: int, short_output: Optional[bool] = False): r_result = model_to_dict(this_result, recurse=not short_output) else: r_result = None - db.close() return r_result @@ -149,10 +147,8 @@ async def patch_result( if this_result.save() == 1: r_result = model_to_dict(this_result) - db.close() return r_result else: - db.close() raise HTTPException( status_code=500, detail=f"Unable to patch result {result_id}" ) @@ -192,7 +188,6 @@ async def post_results(result_list: ResultList, token: str = Depends(oauth2_sche with db.atomic(): for batch in chunked(new_results, 15): Result.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_results)} results" @@ -206,11 +201,9 @@ async def delete_result(result_id: int, token: str = Depends(oauth2_scheme)): this_result = Result.get_or_none(Result.id == result_id) if not this_result: - db.close() raise HTTPException(status_code=404, detail=f"Result ID {result_id} not found") count = this_result.delete_instance() - db.close() if count == 1: return f"Result {result_id} has been deleted" diff --git a/app/routers_v3/sbaplayers.py b/app/routers_v3/sbaplayers.py index 0810784..255894f 100644 --- a/app/routers_v3/sbaplayers.py +++ b/app/routers_v3/sbaplayers.py @@ -102,7 +102,6 @@ async def get_players( if csv: return_val = query_to_csv(all_players) - db.close() return Response(content=return_val, media_type="text/csv") total_count = all_players.count() @@ -112,7 +111,6 @@ async def get_players( "count": total_count, "players": [model_to_dict(x) for x in all_players], } - db.close() return return_val @@ -121,13 +119,11 @@ async def get_players( async def get_one_player(player_id: int): this_player = SbaPlayer.get_or_none(SbaPlayer.id == player_id) if this_player is None: - db.close() raise HTTPException( status_code=404, detail=f"SbaPlayer id {player_id} not found" ) r_data = model_to_dict(this_player) - db.close() return r_data @@ -145,7 +141,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.", @@ -153,7 +148,6 @@ async def patch_player( this_player = SbaPlayer.get_or_none(SbaPlayer.id == player_id) if this_player is None: - db.close() raise HTTPException( status_code=404, detail=f"SbaPlayer id {player_id} not found" ) @@ -173,10 +167,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", @@ -188,7 +180,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.", @@ -207,7 +198,6 @@ async def post_players(players: PlayerList, token: str = Depends(oauth2_scheme)) ) if dupes.count() > 0: logger.error(f"Found a dupe for {x}") - db.close() raise HTTPException( status_code=400, detail=f"{x.first_name} {x.last_name} has a key already in the database", @@ -218,7 +208,6 @@ async def post_players(players: PlayerList, token: str = Depends(oauth2_scheme)) with db.atomic(): for batch in chunked(new_players, 15): SbaPlayer.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_players)} new MLB players" @@ -228,7 +217,6 @@ async def post_players(players: PlayerList, token: str = Depends(oauth2_scheme)) async def post_one_player(player: SbaPlayerModel, 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.", @@ -243,7 +231,6 @@ async def post_one_player(player: SbaPlayerModel, token: str = Depends(oauth2_sc logging.info(f"POST /SbaPlayers/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", @@ -253,10 +240,8 @@ async def post_one_player(player: SbaPlayerModel, token: str = Depends(oauth2_sc saved = new_player.save() if saved == 1: return_val = model_to_dict(new_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", @@ -268,7 +253,6 @@ async def post_one_player(player: SbaPlayerModel, token: str = Depends(oauth2_sc 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 +260,11 @@ async def delete_player(player_id: int, token: str = Depends(oauth2_scheme)): this_player = SbaPlayer.get_or_none(SbaPlayer.id == player_id) if this_player is None: - db.close() raise HTTPException( status_code=404, detail=f"SbaPlayer id {player_id} not found" ) count = this_player.delete_instance() - db.close() if count == 1: return f"Player {player_id} has been deleted" diff --git a/app/routers_v3/schedules.py b/app/routers_v3/schedules.py index 03fcac9..59924fe 100644 --- a/app/routers_v3/schedules.py +++ b/app/routers_v3/schedules.py @@ -80,7 +80,6 @@ async def get_schedules( "count": total_count, "schedules": [model_to_dict(x, recurse=not short_output) for x in all_sched], } - db.close() return return_sched @@ -92,7 +91,6 @@ async def get_one_schedule(schedule_id: int): r_sched = model_to_dict(this_sched) else: r_sched = None - db.close() return r_sched @@ -134,10 +132,8 @@ async def patch_schedule( if this_sched.save() == 1: r_sched = model_to_dict(this_sched) - db.close() return r_sched else: - db.close() raise HTTPException( status_code=500, detail=f"Unable to patch schedule {schedule_id}" ) @@ -177,7 +173,6 @@ async def post_schedules(sched_list: ScheduleList, token: str = Depends(oauth2_s with db.atomic(): for batch in chunked(new_sched, 15): Schedule.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_sched)} schedules" @@ -196,7 +191,6 @@ async def delete_schedule(schedule_id: int, token: str = Depends(oauth2_scheme)) ) count = this_sched.delete_instance() - db.close() if count == 1: return f"Schedule {this_sched} has been deleted" diff --git a/app/routers_v3/standings.py b/app/routers_v3/standings.py index aa06ece..dbe0c32 100644 --- a/app/routers_v3/standings.py +++ b/app/routers_v3/standings.py @@ -69,7 +69,6 @@ async def get_standings( "standings": [model_to_dict(x, recurse=not short_output) for x in div_teams], } - db.close() return return_standings @@ -100,7 +99,6 @@ async def patch_standings( try: this_stan = Standings.get_by_id(stan_id) except Exception as e: - db.close() raise HTTPException(status_code=404, detail=f"No team found with id {stan_id}") if wins: @@ -109,7 +107,6 @@ async def patch_standings( this_stan.losses = losses this_stan.save() - db.close() return model_to_dict(this_stan) @@ -129,7 +126,6 @@ async def post_standings(season: int, token: str = Depends(oauth2_scheme)): with db.atomic(): for batch in chunked(new_teams, 16): Standings.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_teams)} standings" @@ -142,7 +138,6 @@ async def recalculate_standings(season: int, token: str = Depends(oauth2_scheme) raise HTTPException(status_code=401, detail="Unauthorized") code = Standings.recalculate(season) - db.close() if code == 69: raise HTTPException(status_code=500, detail=f"Error recreating Standings rows") return f"Just recalculated standings for season {season}" diff --git a/app/routers_v3/stratgame.py b/app/routers_v3/stratgame.py index 9246c97..7f42773 100644 --- a/app/routers_v3/stratgame.py +++ b/app/routers_v3/stratgame.py @@ -129,7 +129,6 @@ async def get_games( "count": total_count, "games": [model_to_dict(x, recurse=not short_output) for x in all_games], } - db.close() return return_games @@ -138,11 +137,9 @@ async def get_games( async def get_one_game(game_id: int) -> Any: 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 @@ -164,7 +161,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 game_num is not None: @@ -259,7 +255,6 @@ async def post_games(game_list: GameList, token: str = Depends(oauth2_scheme)) - with db.atomic(): for batch in chunked(new_games, 16): StratGame.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_games)} games" @@ -273,7 +268,6 @@ async def wipe_game(game_id: int, token: str = Depends(oauth2_scheme)) -> Any: 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") this_game.away_score = None @@ -284,10 +278,8 @@ async def wipe_game(game_id: int, token: str = Depends(oauth2_scheme)) -> Any: 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 wipe game {game_id}") @@ -300,11 +292,9 @@ async def delete_game(game_id: int, token: str = Depends(oauth2_scheme)) -> Any: 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_v3/stratplay/batting.py b/app/routers_v3/stratplay/batting.py index 9a7fa2c..150585b 100644 --- a/app/routers_v3/stratplay/batting.py +++ b/app/routers_v3/stratplay/batting.py @@ -598,5 +598,4 @@ async def get_batting_totals( } ) - db.close() return return_stats diff --git a/app/routers_v3/stratplay/crud.py b/app/routers_v3/stratplay/crud.py index ee56f51..dde61f7 100644 --- a/app/routers_v3/stratplay/crud.py +++ b/app/routers_v3/stratplay/crud.py @@ -20,10 +20,8 @@ logger = logging.getLogger("discord_app") @handle_db_errors 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 @@ -37,12 +35,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 @@ -93,7 +89,6 @@ async def post_plays(p_list: PlayList, token: str = Depends(oauth2_scheme)): with db.atomic(): for batch in chunked(new_plays, 20): StratPlay.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"Inserted {len(new_plays)} plays" @@ -107,11 +102,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" @@ -130,11 +123,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}" @@ -155,5 +146,4 @@ async def post_erun_check(token: str = Depends(oauth2_scheme)): (StratPlay.e_run == 1) & (StratPlay.run == 0) ) count = all_plays.execute() - db.close() return count diff --git a/app/routers_v3/stratplay/fielding.py b/app/routers_v3/stratplay/fielding.py index 69ea587..26fb1cb 100644 --- a/app/routers_v3/stratplay/fielding.py +++ b/app/routers_v3/stratplay/fielding.py @@ -365,5 +365,4 @@ async def get_fielding_totals( "week": this_week, } ) - db.close() return return_stats diff --git a/app/routers_v3/stratplay/pitching.py b/app/routers_v3/stratplay/pitching.py index c588ae5..ac0207b 100644 --- a/app/routers_v3/stratplay/pitching.py +++ b/app/routers_v3/stratplay/pitching.py @@ -352,7 +352,6 @@ async def get_pitching_totals( ) return_stats["count"] = len(return_stats["stats"]) - db.close() if csv: return Response( content=complex_data_to_csv(return_stats["stats"]), media_type="text/csv" diff --git a/app/routers_v3/stratplay/plays.py b/app/routers_v3/stratplay/plays.py index 37e9943..e6a609b 100644 --- a/app/routers_v3/stratplay/plays.py +++ b/app/routers_v3/stratplay/plays.py @@ -210,5 +210,4 @@ 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 diff --git a/app/routers_v3/transactions.py b/app/routers_v3/transactions.py index 21a3c9b..ee02de8 100644 --- a/app/routers_v3/transactions.py +++ b/app/routers_v3/transactions.py @@ -101,7 +101,6 @@ async def get_transactions( ], } - db.close() return return_trans @@ -119,7 +118,6 @@ async def patch_transactions( these_moves = Transaction.select().where(Transaction.moveid == move_id) if these_moves.count() == 0: - db.close() raise HTTPException(status_code=404, detail=f"Move ID {move_id} not found") if frozen is not None: @@ -131,7 +129,6 @@ async def patch_transactions( x.cancelled = cancelled x.save() - db.close() return f"Updated {these_moves.count()} transactions" @@ -181,7 +178,6 @@ async def post_transactions( for batch in chunked(all_moves, 15): Transaction.insert_many(batch).on_conflict_ignore().execute() - db.close() return f"{len(all_moves)} transactions have been added" @@ -195,7 +191,6 @@ async def delete_transactions(move_id, token: str = Depends(oauth2_scheme)): delete_query = Transaction.delete().where(Transaction.moveid == move_id) count = delete_query.execute() - db.close() if count > 0: return f"Removed {count} transactions" else: