Merge pull request 'fix: replace 467 manual db.close() calls with middleware (#30)' (#33) from ai/paper-dynasty-database#30 into next-release

Reviewed-on: #33
This commit is contained in:
cal 2026-03-03 21:53:37 +00:00
commit 761c0a6dab
31 changed files with 37 additions and 512 deletions

View File

@ -5,6 +5,7 @@ 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,
@ -78,6 +79,17 @@ 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):
return get_swagger_ui_html(

View File

@ -1,7 +1,7 @@
from fastapi import APIRouter, Depends, HTTPException
import logging
from ..db_engine import db, Player
from ..db_engine import Player
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA, PRIVATE_IN_SCHEMA
logging.basicConfig(
@ -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'}

View File

@ -4,7 +4,7 @@ import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Award, model_to_dict
from ..db_engine import Award, model_to_dict
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA, PRIVATE_IN_SCHEMA
logging.basicConfig(
@ -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')

View File

@ -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')

View File

@ -2,8 +2,7 @@ import os
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from fastapi.responses import FileResponse
from scipy import stats
from typing import Literal, Optional, List
from typing import Literal, List
import logging
import pandas as pd
import pydantic
@ -13,10 +12,8 @@ from ..db_engine import (
db,
BattingCardRatings,
model_to_dict,
chunked,
BattingCard,
Player,
query_to_csv,
Team,
CardPosition,
)
@ -158,7 +155,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 +191,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 +202,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 +322,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 +333,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 +355,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 +391,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 +637,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 +660,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 +680,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 +687,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 +714,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 +721,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"

View File

@ -5,7 +5,7 @@ from typing import Literal, Optional, List
import logging
import pydantic
from ..db_engine import db, BattingCard, model_to_dict, fn, chunked, Player, MlbPlayer
from ..db_engine import db, BattingCard, model_to_dict, fn, Player, MlbPlayer
from ..db_helpers import upsert_batting_cards
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
@ -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.",

View File

@ -4,7 +4,7 @@ import logging
import pydantic
from pydantic import root_validator
from ..db_engine import db, CardPosition, model_to_dict, chunked, Player, fn
from ..db_engine import db, CardPosition, model_to_dict, Player, fn
from ..db_helpers import upsert_card_positions
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
@ -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"

View File

@ -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:
@ -146,12 +140,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
@ -159,7 +151,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.'
@ -194,7 +185,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')
@ -218,7 +208,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'
@ -251,14 +240,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}')
@ -266,7 +253,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.'
@ -280,7 +266,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.'
@ -293,7 +278,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'
@ -304,7 +288,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.'
@ -312,7 +295,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:
@ -337,10 +319,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'
@ -351,7 +331,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.'
@ -359,11 +338,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')

View File

@ -4,7 +4,7 @@ import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Cardset, model_to_dict, fn, Event
from ..db_engine import Cardset, model_to_dict, fn, Event
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -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')

View File

@ -4,7 +4,7 @@ from typing import Optional
import logging
import pydantic
from ..db_engine import db, Current, model_to_dict
from ..db_engine import Current, model_to_dict
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA, PRIVATE_IN_SCHEMA
logging.basicConfig(
@ -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')

View File

@ -1,6 +1,5 @@
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from typing import List, Optional, Literal
import copy
from typing import List, Optional
import logging
import pandas as pd
import pydantic
@ -11,7 +10,6 @@ from ..db_engine import (
StratGame,
Player,
model_to_dict,
chunked,
fn,
Team,
Card,
@ -112,7 +110,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 +133,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 +185,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 +211,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 +236,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 +269,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 +281,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 +303,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}"

View File

@ -4,7 +4,7 @@ import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Event, model_to_dict, fn
from ..db_engine import Event, model_to_dict, fn
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -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')

View File

@ -4,7 +4,7 @@ import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, GameRewards, model_to_dict
from ..db_engine import GameRewards, model_to_dict
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -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')

View File

@ -3,7 +3,7 @@ from typing import Optional, List
import logging
import pydantic
from ..db_engine import db, GauntletReward, model_to_dict, chunked, DatabaseError
from ..db_engine import db, GauntletReward, model_to_dict, DatabaseError
from ..db_helpers import upsert_gauntlet_rewards
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
@ -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"

View File

@ -4,7 +4,7 @@ from typing import Optional
import logging
import pydantic
from ..db_engine import db, GauntletRun, model_to_dict, DatabaseError
from ..db_engine import GauntletRun, model_to_dict, DatabaseError
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -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')

View File

@ -5,17 +5,14 @@ from fastapi import APIRouter, Depends, HTTPException, Response, Query
from typing import Optional, List
import logging
import pydantic
from pandas import DataFrame
from ..db_engine import (
db,
MlbPlayer,
Player,
BattingCard,
PitchingCard,
model_to_dict,
fn,
chunked,
query_to_csv,
)
from ..db_helpers import upsert_mlb_players
@ -111,14 +108,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 +121,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 +143,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 +150,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 +171,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 +183,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 +197,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 +208,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 +216,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 +230,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 +239,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 +251,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 +258,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 +281,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 +306,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 +316,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 +337,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"

View File

@ -5,7 +5,7 @@ import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Notification, model_to_dict, fn
from ..db_engine import Notification, model_to_dict, fn
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -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')

View File

@ -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')

View File

@ -4,7 +4,7 @@ import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, PackType, model_to_dict, fn
from ..db_engine import PackType, model_to_dict, fn
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -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')

View File

@ -5,7 +5,7 @@ import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Paperdex, model_to_dict, Player, Cardset, Team
from ..db_engine import Paperdex, model_to_dict, Player, Cardset, Team
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -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'

View File

@ -2,7 +2,7 @@ import os
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from fastapi.responses import FileResponse
from typing import Literal, Optional, List
from typing import Literal, List
import logging
import pandas as pd
import pydantic
@ -12,7 +12,6 @@ from ..db_engine import (
db,
PitchingCardRatings,
model_to_dict,
chunked,
PitchingCard,
Player,
query_to_csv,
@ -153,7 +152,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 +175,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 +184,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 +242,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 +253,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 +275,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 +311,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 +490,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 +524,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 +531,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 +558,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 +565,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"

View File

@ -5,7 +5,7 @@ from typing import Literal, Optional, List
import logging
import pydantic
from ..db_engine import db, PitchingCard, model_to_dict, chunked, Player, fn, MlbPlayer
from ..db_engine import db, PitchingCard, model_to_dict, Player, fn, MlbPlayer
from ..db_helpers import upsert_pitching_cards
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
@ -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.",

View File

@ -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')

View File

@ -1,12 +1,10 @@
import datetime
import os.path
import base64
import pandas as pd
from fastapi import APIRouter, Depends, HTTPException, Request, Response, Query
from fastapi.responses import FileResponse
from fastapi.templating import Jinja2Templates
from html2image import Html2Image
from typing import Optional, List, Literal
import logging
import pydantic
@ -19,7 +17,6 @@ from ..db_engine import (
Player,
model_to_dict,
fn,
chunked,
Paperdex,
Cardset,
Rarity,
@ -152,7 +149,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 +235,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 +323,6 @@ async def get_players(
# return_val['players'].append(model_to_dict(x, recurse=not flat))
db.close()
return return_val
@ -479,7 +473,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 +490,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 +583,6 @@ async def search_players(
return_val["players"].append(this_record)
db.close()
return return_val
@ -600,7 +591,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 +650,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 +657,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 +674,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 +688,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 +774,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 +828,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 +866,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 +874,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 +897,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 +905,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 +966,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 +978,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 +1046,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 +1057,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 +1067,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 +1079,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 +1088,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 +1095,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 +1115,6 @@ async def post_image_reset(
this_player.save()
r_player = model_to_dict(this_player)
db.close()
return r_player
@ -1151,7 +1122,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 +1130,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(

View File

@ -4,7 +4,7 @@ import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Rarity, model_to_dict, fn
from ..db_engine import Rarity, model_to_dict, fn
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -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')

View File

@ -4,7 +4,7 @@ import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Result, model_to_dict, Team, DataError
from ..db_engine import Result, model_to_dict, Team, DataError
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -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')

View File

@ -5,7 +5,7 @@ import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Reward, model_to_dict, fn
from ..db_engine import Reward, model_to_dict, fn
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -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')

View File

@ -1,13 +1,9 @@
import csv
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Response, Query
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
import logging
import pydantic
import pandas as pd
from ..db_engine import db, model_to_dict, fn, query_to_csv, complex_data_to_csv, Player, BattingCardRatings
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA, int_timestamp
from ..db_engine import Player
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
from ..player_scouting import get_player_ids
logging.basicConfig(
@ -50,7 +46,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 +53,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 +87,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.'

View File

@ -1,11 +1,10 @@
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from typing import Literal, Optional, List
from typing import Optional, List
import logging
import pandas as pd
import pydantic
from pydantic import validator
from ..db_engine import db, StratGame, model_to_dict, chunked, PitchingCard, Player, query_to_csv, Team, fn
from ..db_engine import StratGame, model_to_dict, fn
from ..dependencies import oauth2_scheme, valid_token, LOG_DATA
logging.basicConfig(
@ -83,7 +82,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 +92,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 +99,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 +115,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 +126,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 +142,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 +158,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'

View File

@ -13,11 +13,9 @@ from ..db_engine import (
Team,
Player,
model_to_dict,
chunked,
fn,
SQL,
Case,
complex_data_to_csv,
Decision,
)
from ..db_helpers import upsert_strat_plays
@ -367,7 +365,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 +373,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 +804,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 +1169,6 @@ async def get_pitching_totals(
"rbi%": rbi_rate,
}
)
db.close()
if csv:
return_vals = return_stats["stats"]
@ -1209,7 +1202,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 +1219,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 +1396,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 +1410,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 +1463,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 +1475,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 +1495,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}"

View File

@ -36,7 +36,6 @@ from ..dependencies import (
oauth2_scheme,
valid_token,
LOG_DATA,
int_timestamp,
PRIVATE_IN_SCHEMA,
)
@ -166,7 +165,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:
@ -174,7 +172,6 @@ async def get_teams(
for x in all_teams:
return_teams["teams"].append(model_to_dict(x))
db.close()
return return_teams
@ -183,7 +180,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(
@ -198,7 +194,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
@ -287,7 +282,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"]
@ -314,11 +308,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",
@ -332,7 +324,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",
@ -631,11 +622,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",
@ -646,7 +635,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",
@ -710,13 +698,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
@ -729,13 +715,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(
@ -758,11 +742,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",
@ -776,7 +758,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",
@ -848,7 +829,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":
@ -873,7 +853,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:
@ -907,7 +886,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":
@ -932,7 +910,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")
@ -948,7 +925,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}")
@ -1034,7 +1010,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
@ -1043,12 +1018,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.",
@ -1065,7 +1038,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} /// "
@ -1078,7 +1050,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 "
@ -1135,7 +1106,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}"
)
@ -1143,12 +1113,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()}"
@ -1161,7 +1129,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 "
@ -1189,7 +1156,6 @@ async def team_buy_packs(
with db.atomic():
Pack.bulk_create(all_packs, batch_size=15)
db.close()
raise HTTPException(
status_code=200,
@ -1203,12 +1169,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.",
@ -1223,7 +1187,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}"
)
@ -1292,11 +1255,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.",
@ -1310,11 +1271,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"])
@ -1359,7 +1318,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.",
@ -1367,7 +1325,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}",
@ -1395,7 +1352,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(
@ -1408,7 +1364,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.",
@ -1420,7 +1375,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}"
@ -1433,7 +1387,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.",
@ -1442,14 +1395,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(
@ -1481,7 +1432,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.",
@ -1489,7 +1439,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:
@ -1533,7 +1482,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(
@ -1546,7 +1494,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.",
@ -1554,11 +1501,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")