fix: eliminate N+1 queries in batch POST endpoints (#25) #52
@ -3,15 +3,27 @@ from typing import List, Optional, Literal
|
|||||||
import logging
|
import logging
|
||||||
import pydantic
|
import pydantic
|
||||||
|
|
||||||
from ..db_engine import db, BattingStat, Team, Player, Current, model_to_dict, chunked, fn, per_season_weeks
|
from ..db_engine import (
|
||||||
from ..dependencies import oauth2_scheme, valid_token, PRIVATE_IN_SCHEMA, handle_db_errors
|
db,
|
||||||
|
BattingStat,
|
||||||
logger = logging.getLogger('discord_app')
|
Team,
|
||||||
|
Player,
|
||||||
router = APIRouter(
|
Current,
|
||||||
prefix='/api/v3/battingstats',
|
model_to_dict,
|
||||||
tags=['battingstats']
|
chunked,
|
||||||
|
fn,
|
||||||
|
per_season_weeks,
|
||||||
)
|
)
|
||||||
|
from ..dependencies import (
|
||||||
|
oauth2_scheme,
|
||||||
|
valid_token,
|
||||||
|
PRIVATE_IN_SCHEMA,
|
||||||
|
handle_db_errors,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("discord_app")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/v3/battingstats", tags=["battingstats"])
|
||||||
|
|
||||||
|
|
||||||
class BatStatModel(pydantic.BaseModel):
|
class BatStatModel(pydantic.BaseModel):
|
||||||
@ -60,29 +72,37 @@ class BatStatList(pydantic.BaseModel):
|
|||||||
stats: List[BatStatModel]
|
stats: List[BatStatModel]
|
||||||
|
|
||||||
|
|
||||||
@router.get('')
|
@router.get("")
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def get_batstats(
|
async def get_batstats(
|
||||||
season: int, s_type: Optional[str] = 'regular', team_abbrev: list = Query(default=None),
|
season: int,
|
||||||
player_name: list = Query(default=None), player_id: list = Query(default=None),
|
s_type: Optional[str] = "regular",
|
||||||
week_start: Optional[int] = None, week_end: Optional[int] = None, game_num: list = Query(default=None),
|
team_abbrev: list = Query(default=None),
|
||||||
position: list = Query(default=None), limit: Optional[int] = None, sort: Optional[str] = None,
|
player_name: list = Query(default=None),
|
||||||
short_output: Optional[bool] = True):
|
player_id: list = Query(default=None),
|
||||||
if 'post' in s_type.lower():
|
week_start: Optional[int] = None,
|
||||||
|
week_end: Optional[int] = None,
|
||||||
|
game_num: list = Query(default=None),
|
||||||
|
position: list = Query(default=None),
|
||||||
|
limit: Optional[int] = None,
|
||||||
|
sort: Optional[str] = None,
|
||||||
|
short_output: Optional[bool] = True,
|
||||||
|
):
|
||||||
|
if "post" in s_type.lower():
|
||||||
all_stats = BattingStat.post_season(season)
|
all_stats = BattingStat.post_season(season)
|
||||||
if all_stats.count() == 0:
|
if all_stats.count() == 0:
|
||||||
db.close()
|
db.close()
|
||||||
return {'count': 0, 'stats': []}
|
return {"count": 0, "stats": []}
|
||||||
elif s_type.lower() in ['combined', 'total', 'all']:
|
elif s_type.lower() in ["combined", "total", "all"]:
|
||||||
all_stats = BattingStat.combined_season(season)
|
all_stats = BattingStat.combined_season(season)
|
||||||
if all_stats.count() == 0:
|
if all_stats.count() == 0:
|
||||||
db.close()
|
db.close()
|
||||||
return {'count': 0, 'stats': []}
|
return {"count": 0, "stats": []}
|
||||||
else:
|
else:
|
||||||
all_stats = BattingStat.regular_season(season)
|
all_stats = BattingStat.regular_season(season)
|
||||||
if all_stats.count() == 0:
|
if all_stats.count() == 0:
|
||||||
db.close()
|
db.close()
|
||||||
return {'count': 0, 'stats': []}
|
return {"count": 0, "stats": []}
|
||||||
|
|
||||||
if position is not None:
|
if position is not None:
|
||||||
all_stats = all_stats.where(BattingStat.pos << [x.upper() for x in position])
|
all_stats = all_stats.where(BattingStat.pos << [x.upper() for x in position])
|
||||||
@ -93,7 +113,9 @@ async def get_batstats(
|
|||||||
if player_id:
|
if player_id:
|
||||||
all_stats = all_stats.where(BattingStat.player_id << player_id)
|
all_stats = all_stats.where(BattingStat.player_id << player_id)
|
||||||
else:
|
else:
|
||||||
p_query = Player.select_season(season).where(fn.Lower(Player.name) << [x.lower() for x in player_name])
|
p_query = Player.select_season(season).where(
|
||||||
|
fn.Lower(Player.name) << [x.lower() for x in player_name]
|
||||||
|
)
|
||||||
all_stats = all_stats.where(BattingStat.player << p_query)
|
all_stats = all_stats.where(BattingStat.player << p_query)
|
||||||
if game_num:
|
if game_num:
|
||||||
all_stats = all_stats.where(BattingStat.game == game_num)
|
all_stats = all_stats.where(BattingStat.game == game_num)
|
||||||
@ -108,21 +130,19 @@ async def get_batstats(
|
|||||||
db.close()
|
db.close()
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=404,
|
status_code=404,
|
||||||
detail=f'Start week {start} is after end week {end} - cannot pull stats'
|
detail=f"Start week {start} is after end week {end} - cannot pull stats",
|
||||||
)
|
)
|
||||||
all_stats = all_stats.where(
|
all_stats = all_stats.where((BattingStat.week >= start) & (BattingStat.week <= end))
|
||||||
(BattingStat.week >= start) & (BattingStat.week <= end)
|
|
||||||
)
|
|
||||||
|
|
||||||
if limit:
|
if limit:
|
||||||
all_stats = all_stats.limit(limit)
|
all_stats = all_stats.limit(limit)
|
||||||
if sort:
|
if sort:
|
||||||
if sort == 'newest':
|
if sort == "newest":
|
||||||
all_stats = all_stats.order_by(-BattingStat.week, -BattingStat.game)
|
all_stats = all_stats.order_by(-BattingStat.week, -BattingStat.game)
|
||||||
|
|
||||||
return_stats = {
|
return_stats = {
|
||||||
'count': all_stats.count(),
|
"count": all_stats.count(),
|
||||||
'stats': [model_to_dict(x, recurse=not short_output) for x in all_stats],
|
"stats": [model_to_dict(x, recurse=not short_output) for x in all_stats],
|
||||||
# 'stats': [{'id': x.id} for x in all_stats]
|
# 'stats': [{'id': x.id} for x in all_stats]
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -130,52 +150,82 @@ async def get_batstats(
|
|||||||
return return_stats
|
return return_stats
|
||||||
|
|
||||||
|
|
||||||
@router.get('/totals')
|
@router.get("/totals")
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def get_totalstats(
|
async def get_totalstats(
|
||||||
season: int, s_type: Literal['regular', 'post', 'total', None] = None, team_abbrev: list = Query(default=None),
|
season: int,
|
||||||
team_id: list = Query(default=None), player_name: list = Query(default=None),
|
s_type: Literal["regular", "post", "total", None] = None,
|
||||||
week_start: Optional[int] = None, week_end: Optional[int] = None, game_num: list = Query(default=None),
|
team_abbrev: list = Query(default=None),
|
||||||
position: list = Query(default=None), sort: Optional[str] = None, player_id: list = Query(default=None),
|
team_id: list = Query(default=None),
|
||||||
group_by: Literal['team', 'player', 'playerteam'] = 'player', short_output: Optional[bool] = False,
|
player_name: list = Query(default=None),
|
||||||
min_pa: Optional[int] = 1, week: list = Query(default=None)):
|
week_start: Optional[int] = None,
|
||||||
|
week_end: Optional[int] = None,
|
||||||
|
game_num: list = Query(default=None),
|
||||||
|
position: list = Query(default=None),
|
||||||
|
sort: Optional[str] = None,
|
||||||
|
player_id: list = Query(default=None),
|
||||||
|
group_by: Literal["team", "player", "playerteam"] = "player",
|
||||||
|
short_output: Optional[bool] = False,
|
||||||
|
min_pa: Optional[int] = 1,
|
||||||
|
week: list = Query(default=None),
|
||||||
|
):
|
||||||
if sum(1 for x in [s_type, (week_start or week_end), week] if x is not None) > 1:
|
if sum(1 for x in [s_type, (week_start or week_end), week] if x is not None) > 1:
|
||||||
raise HTTPException(status_code=400, detail=f'Only one of s_type, week_start/week_end, or week may be used.')
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Only one of s_type, week_start/week_end, or week may be used.",
|
||||||
|
)
|
||||||
|
|
||||||
# Build SELECT fields conditionally based on group_by to match GROUP BY exactly
|
# Build SELECT fields conditionally based on group_by to match GROUP BY exactly
|
||||||
select_fields = []
|
select_fields = []
|
||||||
|
|
||||||
if group_by == 'player':
|
if group_by == "player":
|
||||||
select_fields = [BattingStat.player]
|
select_fields = [BattingStat.player]
|
||||||
elif group_by == 'team':
|
elif group_by == "team":
|
||||||
select_fields = [BattingStat.team]
|
select_fields = [BattingStat.team]
|
||||||
elif group_by == 'playerteam':
|
elif group_by == "playerteam":
|
||||||
select_fields = [BattingStat.player, BattingStat.team]
|
select_fields = [BattingStat.player, BattingStat.team]
|
||||||
else:
|
else:
|
||||||
# Default case
|
# Default case
|
||||||
select_fields = [BattingStat.player]
|
select_fields = [BattingStat.player]
|
||||||
|
|
||||||
all_stats = (
|
all_stats = (
|
||||||
BattingStat
|
BattingStat.select(
|
||||||
.select(*select_fields,
|
*select_fields,
|
||||||
fn.SUM(BattingStat.pa).alias('sum_pa'), fn.SUM(BattingStat.ab).alias('sum_ab'),
|
fn.SUM(BattingStat.pa).alias("sum_pa"),
|
||||||
fn.SUM(BattingStat.run).alias('sum_run'), fn.SUM(BattingStat.hit).alias('sum_hit'),
|
fn.SUM(BattingStat.ab).alias("sum_ab"),
|
||||||
fn.SUM(BattingStat.rbi).alias('sum_rbi'), fn.SUM(BattingStat.double).alias('sum_double'),
|
fn.SUM(BattingStat.run).alias("sum_run"),
|
||||||
fn.SUM(BattingStat.triple).alias('sum_triple'), fn.SUM(BattingStat.hr).alias('sum_hr'),
|
fn.SUM(BattingStat.hit).alias("sum_hit"),
|
||||||
fn.SUM(BattingStat.bb).alias('sum_bb'), fn.SUM(BattingStat.so).alias('sum_so'),
|
fn.SUM(BattingStat.rbi).alias("sum_rbi"),
|
||||||
fn.SUM(BattingStat.hbp).alias('sum_hbp'), fn.SUM(BattingStat.sac).alias('sum_sac'),
|
fn.SUM(BattingStat.double).alias("sum_double"),
|
||||||
fn.SUM(BattingStat.ibb).alias('sum_ibb'), fn.SUM(BattingStat.gidp).alias('sum_gidp'),
|
fn.SUM(BattingStat.triple).alias("sum_triple"),
|
||||||
fn.SUM(BattingStat.sb).alias('sum_sb'), fn.SUM(BattingStat.cs).alias('sum_cs'),
|
fn.SUM(BattingStat.hr).alias("sum_hr"),
|
||||||
fn.SUM(BattingStat.bphr).alias('sum_bphr'), fn.SUM(BattingStat.bpfo).alias('sum_bpfo'),
|
fn.SUM(BattingStat.bb).alias("sum_bb"),
|
||||||
fn.SUM(BattingStat.bp1b).alias('sum_bp1b'), fn.SUM(BattingStat.bplo).alias('sum_bplo'),
|
fn.SUM(BattingStat.so).alias("sum_so"),
|
||||||
fn.SUM(BattingStat.xba).alias('sum_xba'), fn.SUM(BattingStat.xbt).alias('sum_xbt'),
|
fn.SUM(BattingStat.hbp).alias("sum_hbp"),
|
||||||
fn.SUM(BattingStat.xch).alias('sum_xch'), fn.SUM(BattingStat.xhit).alias('sum_xhit'),
|
fn.SUM(BattingStat.sac).alias("sum_sac"),
|
||||||
fn.SUM(BattingStat.error).alias('sum_error'), fn.SUM(BattingStat.pb).alias('sum_pb'),
|
fn.SUM(BattingStat.ibb).alias("sum_ibb"),
|
||||||
fn.SUM(BattingStat.sbc).alias('sum_sbc'), fn.SUM(BattingStat.csc).alias('sum_csc'),
|
fn.SUM(BattingStat.gidp).alias("sum_gidp"),
|
||||||
fn.SUM(BattingStat.roba).alias('sum_roba'), fn.SUM(BattingStat.robs).alias('sum_robs'),
|
fn.SUM(BattingStat.sb).alias("sum_sb"),
|
||||||
fn.SUM(BattingStat.raa).alias('sum_raa'), fn.SUM(BattingStat.rto).alias('sum_rto'))
|
fn.SUM(BattingStat.cs).alias("sum_cs"),
|
||||||
.where(BattingStat.season == season)
|
fn.SUM(BattingStat.bphr).alias("sum_bphr"),
|
||||||
.having(fn.SUM(BattingStat.pa) >= min_pa)
|
fn.SUM(BattingStat.bpfo).alias("sum_bpfo"),
|
||||||
|
fn.SUM(BattingStat.bp1b).alias("sum_bp1b"),
|
||||||
|
fn.SUM(BattingStat.bplo).alias("sum_bplo"),
|
||||||
|
fn.SUM(BattingStat.xba).alias("sum_xba"),
|
||||||
|
fn.SUM(BattingStat.xbt).alias("sum_xbt"),
|
||||||
|
fn.SUM(BattingStat.xch).alias("sum_xch"),
|
||||||
|
fn.SUM(BattingStat.xhit).alias("sum_xhit"),
|
||||||
|
fn.SUM(BattingStat.error).alias("sum_error"),
|
||||||
|
fn.SUM(BattingStat.pb).alias("sum_pb"),
|
||||||
|
fn.SUM(BattingStat.sbc).alias("sum_sbc"),
|
||||||
|
fn.SUM(BattingStat.csc).alias("sum_csc"),
|
||||||
|
fn.SUM(BattingStat.roba).alias("sum_roba"),
|
||||||
|
fn.SUM(BattingStat.robs).alias("sum_robs"),
|
||||||
|
fn.SUM(BattingStat.raa).alias("sum_raa"),
|
||||||
|
fn.SUM(BattingStat.rto).alias("sum_rto"),
|
||||||
|
)
|
||||||
|
.where(BattingStat.season == season)
|
||||||
|
.having(fn.SUM(BattingStat.pa) >= min_pa)
|
||||||
)
|
)
|
||||||
|
|
||||||
if True in [s_type is not None, week_start is not None, week_end is not None]:
|
if True in [s_type is not None, week_start is not None, week_end is not None]:
|
||||||
@ -185,16 +235,20 @@ async def get_totalstats(
|
|||||||
elif week_start is not None or week_end is not None:
|
elif week_start is not None or week_end is not None:
|
||||||
if week_start is None or week_end is None:
|
if week_start is None or week_end is None:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=400, detail='Both week_start and week_end must be included if either is used.'
|
status_code=400,
|
||||||
|
detail="Both week_start and week_end must be included if either is used.",
|
||||||
|
)
|
||||||
|
weeks["start"] = week_start
|
||||||
|
if week_end < weeks["start"]:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="week_end must be greater than or equal to week_start",
|
||||||
)
|
)
|
||||||
weeks['start'] = week_start
|
|
||||||
if week_end < weeks['start']:
|
|
||||||
raise HTTPException(status_code=400, detail='week_end must be greater than or equal to week_start')
|
|
||||||
else:
|
else:
|
||||||
weeks['end'] = week_end
|
weeks["end"] = week_end
|
||||||
|
|
||||||
all_stats = all_stats.where(
|
all_stats = all_stats.where(
|
||||||
(BattingStat.week >= weeks['start']) & (BattingStat.week <= weeks['end'])
|
(BattingStat.week >= weeks["start"]) & (BattingStat.week <= weeks["end"])
|
||||||
)
|
)
|
||||||
elif week is not None:
|
elif week is not None:
|
||||||
all_stats = all_stats.where(BattingStat.week << week)
|
all_stats = all_stats.where(BattingStat.week << week)
|
||||||
@ -204,14 +258,20 @@ async def get_totalstats(
|
|||||||
if position is not None:
|
if position is not None:
|
||||||
p_list = [x.upper() for x in position]
|
p_list = [x.upper() for x in position]
|
||||||
all_players = Player.select().where(
|
all_players = Player.select().where(
|
||||||
(Player.pos_1 << p_list) | (Player.pos_2 << p_list) | (Player.pos_3 << p_list) | ( Player.pos_4 << p_list) |
|
(Player.pos_1 << p_list)
|
||||||
(Player.pos_5 << p_list) | (Player.pos_6 << p_list) | (Player.pos_7 << p_list) | ( Player.pos_8 << p_list)
|
| (Player.pos_2 << p_list)
|
||||||
|
| (Player.pos_3 << p_list)
|
||||||
|
| (Player.pos_4 << p_list)
|
||||||
|
| (Player.pos_5 << p_list)
|
||||||
|
| (Player.pos_6 << p_list)
|
||||||
|
| (Player.pos_7 << p_list)
|
||||||
|
| (Player.pos_8 << p_list)
|
||||||
)
|
)
|
||||||
all_stats = all_stats.where(BattingStat.player << all_players)
|
all_stats = all_stats.where(BattingStat.player << all_players)
|
||||||
if sort is not None:
|
if sort is not None:
|
||||||
if sort == 'player':
|
if sort == "player":
|
||||||
all_stats = all_stats.order_by(BattingStat.player)
|
all_stats = all_stats.order_by(BattingStat.player)
|
||||||
elif sort == 'team':
|
elif sort == "team":
|
||||||
all_stats = all_stats.order_by(BattingStat.team)
|
all_stats = all_stats.order_by(BattingStat.team)
|
||||||
if group_by is not None:
|
if group_by is not None:
|
||||||
# Use the same fields for GROUP BY as we used for SELECT
|
# Use the same fields for GROUP BY as we used for SELECT
|
||||||
@ -227,56 +287,63 @@ async def get_totalstats(
|
|||||||
all_teams = Team.select().where(Team.id << team_id)
|
all_teams = Team.select().where(Team.id << team_id)
|
||||||
all_stats = all_stats.where(BattingStat.team << all_teams)
|
all_stats = all_stats.where(BattingStat.team << all_teams)
|
||||||
elif team_abbrev is not None:
|
elif team_abbrev is not None:
|
||||||
all_teams = Team.select().where(fn.Lower(Team.abbrev) << [x.lower() for x in team_abbrev])
|
all_teams = Team.select().where(
|
||||||
|
fn.Lower(Team.abbrev) << [x.lower() for x in team_abbrev]
|
||||||
|
)
|
||||||
all_stats = all_stats.where(BattingStat.team << all_teams)
|
all_stats = all_stats.where(BattingStat.team << all_teams)
|
||||||
|
|
||||||
if player_name is not None:
|
if player_name is not None:
|
||||||
all_players = Player.select().where(fn.Lower(Player.name) << [x.lower() for x in player_name])
|
all_players = Player.select().where(
|
||||||
|
fn.Lower(Player.name) << [x.lower() for x in player_name]
|
||||||
|
)
|
||||||
all_stats = all_stats.where(BattingStat.player << all_players)
|
all_stats = all_stats.where(BattingStat.player << all_players)
|
||||||
elif player_id is not None:
|
elif player_id is not None:
|
||||||
all_players = Player.select().where(Player.id << player_id)
|
all_players = Player.select().where(Player.id << player_id)
|
||||||
all_stats = all_stats.where(BattingStat.player << all_players)
|
all_stats = all_stats.where(BattingStat.player << all_players)
|
||||||
|
|
||||||
return_stats = {
|
return_stats = {"count": all_stats.count(), "stats": []}
|
||||||
'count': all_stats.count(),
|
|
||||||
'stats': []
|
|
||||||
}
|
|
||||||
|
|
||||||
for x in all_stats:
|
for x in all_stats:
|
||||||
# Handle player field based on grouping with safe access
|
# Handle player field based on grouping with safe access
|
||||||
this_player = 'TOT'
|
this_player = "TOT"
|
||||||
if 'player' in group_by and hasattr(x, 'player'):
|
if "player" in group_by and hasattr(x, "player"):
|
||||||
this_player = x.player_id if short_output else model_to_dict(x.player, recurse=False)
|
this_player = (
|
||||||
|
x.player_id if short_output else model_to_dict(x.player, recurse=False)
|
||||||
|
)
|
||||||
|
|
||||||
# Handle team field based on grouping with safe access
|
# Handle team field based on grouping with safe access
|
||||||
this_team = 'TOT'
|
this_team = "TOT"
|
||||||
if 'team' in group_by and hasattr(x, 'team'):
|
if "team" in group_by and hasattr(x, "team"):
|
||||||
this_team = x.team_id if short_output else model_to_dict(x.team, recurse=False)
|
this_team = (
|
||||||
|
x.team_id if short_output else model_to_dict(x.team, recurse=False)
|
||||||
return_stats['stats'].append({
|
)
|
||||||
'player': this_player,
|
|
||||||
'team': this_team,
|
return_stats["stats"].append(
|
||||||
'pa': x.sum_pa,
|
{
|
||||||
'ab': x.sum_ab,
|
"player": this_player,
|
||||||
'run': x.sum_run,
|
"team": this_team,
|
||||||
'hit': x.sum_hit,
|
"pa": x.sum_pa,
|
||||||
'rbi': x.sum_rbi,
|
"ab": x.sum_ab,
|
||||||
'double': x.sum_double,
|
"run": x.sum_run,
|
||||||
'triple': x.sum_triple,
|
"hit": x.sum_hit,
|
||||||
'hr': x.sum_hr,
|
"rbi": x.sum_rbi,
|
||||||
'bb': x.sum_bb,
|
"double": x.sum_double,
|
||||||
'so': x.sum_so,
|
"triple": x.sum_triple,
|
||||||
'hbp': x.sum_hbp,
|
"hr": x.sum_hr,
|
||||||
'sac': x.sum_sac,
|
"bb": x.sum_bb,
|
||||||
'ibb': x.sum_ibb,
|
"so": x.sum_so,
|
||||||
'gidp': x.sum_gidp,
|
"hbp": x.sum_hbp,
|
||||||
'sb': x.sum_sb,
|
"sac": x.sum_sac,
|
||||||
'cs': x.sum_cs,
|
"ibb": x.sum_ibb,
|
||||||
'bphr': x.sum_bphr,
|
"gidp": x.sum_gidp,
|
||||||
'bpfo': x.sum_bpfo,
|
"sb": x.sum_sb,
|
||||||
'bp1b': x.sum_bp1b,
|
"cs": x.sum_cs,
|
||||||
'bplo': x.sum_bplo
|
"bphr": x.sum_bphr,
|
||||||
})
|
"bpfo": x.sum_bpfo,
|
||||||
|
"bp1b": x.sum_bp1b,
|
||||||
|
"bplo": x.sum_bplo,
|
||||||
|
}
|
||||||
|
)
|
||||||
db.close()
|
db.close()
|
||||||
return return_stats
|
return return_stats
|
||||||
|
|
||||||
@ -287,15 +354,17 @@ async def get_totalstats(
|
|||||||
# pass # Keep Career Stats table and recalculate after posting stats
|
# pass # Keep Career Stats table and recalculate after posting stats
|
||||||
|
|
||||||
|
|
||||||
@router.patch('/{stat_id}', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.patch("/{stat_id}", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def patch_batstats(stat_id: int, new_stats: BatStatModel, token: str = Depends(oauth2_scheme)):
|
async def patch_batstats(
|
||||||
|
stat_id: int, new_stats: BatStatModel, token: str = Depends(oauth2_scheme)
|
||||||
|
):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'patch_batstats - Bad Token: {token}')
|
logger.warning(f"patch_batstats - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
if BattingStat.get_or_none(BattingStat.id == stat_id) is None:
|
if BattingStat.get_or_none(BattingStat.id == stat_id) is None:
|
||||||
raise HTTPException(status_code=404, detail=f'Stat ID {stat_id} not found')
|
raise HTTPException(status_code=404, detail=f"Stat ID {stat_id} not found")
|
||||||
|
|
||||||
BattingStat.update(**new_stats.dict()).where(BattingStat.id == stat_id).execute()
|
BattingStat.update(**new_stats.dict()).where(BattingStat.id == stat_id).execute()
|
||||||
r_stat = model_to_dict(BattingStat.get_by_id(stat_id))
|
r_stat = model_to_dict(BattingStat.get_by_id(stat_id))
|
||||||
@ -303,22 +372,37 @@ async def patch_batstats(stat_id: int, new_stats: BatStatModel, token: str = Dep
|
|||||||
return r_stat
|
return r_stat
|
||||||
|
|
||||||
|
|
||||||
@router.post('', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.post("", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def post_batstats(s_list: BatStatList, token: str = Depends(oauth2_scheme)):
|
async def post_batstats(s_list: BatStatList, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'post_batstats - Bad Token: {token}')
|
logger.warning(f"post_batstats - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
all_stats = []
|
all_stats = []
|
||||||
|
|
||||||
|
all_team_ids = list(set(x.team_id for x in s_list.stats))
|
||||||
|
all_player_ids = list(set(x.player_id for x in s_list.stats))
|
||||||
|
found_team_ids = (
|
||||||
|
set(t.id for t in Team.select(Team.id).where(Team.id << all_team_ids))
|
||||||
|
if all_team_ids
|
||||||
|
else set()
|
||||||
|
)
|
||||||
|
found_player_ids = (
|
||||||
|
set(p.id for p in Player.select(Player.id).where(Player.id << all_player_ids))
|
||||||
|
if all_player_ids
|
||||||
|
else set()
|
||||||
|
)
|
||||||
|
|
||||||
for x in s_list.stats:
|
for x in s_list.stats:
|
||||||
team = Team.get_or_none(Team.id == x.team_id)
|
if x.team_id not in found_team_ids:
|
||||||
this_player = Player.get_or_none(Player.id == x.player_id)
|
raise HTTPException(
|
||||||
if team is None:
|
status_code=404, detail=f"Team ID {x.team_id} not found"
|
||||||
raise HTTPException(status_code=404, detail=f'Team ID {x.team_id} not found')
|
)
|
||||||
if this_player is None:
|
if x.player_id not in found_player_ids:
|
||||||
raise HTTPException(status_code=404, detail=f'Player ID {x.player_id} not found')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"Player ID {x.player_id} not found"
|
||||||
|
)
|
||||||
|
|
||||||
all_stats.append(BattingStat(**x.dict()))
|
all_stats.append(BattingStat(**x.dict()))
|
||||||
|
|
||||||
@ -329,4 +413,4 @@ async def post_batstats(s_list: BatStatList, token: str = Depends(oauth2_scheme)
|
|||||||
# Update career stats
|
# Update career stats
|
||||||
|
|
||||||
db.close()
|
db.close()
|
||||||
return f'Added {len(all_stats)} batting lines'
|
return f"Added {len(all_stats)} batting lines"
|
||||||
|
|||||||
@ -4,15 +4,17 @@ import logging
|
|||||||
import pydantic
|
import pydantic
|
||||||
|
|
||||||
from ..db_engine import db, Result, Team, model_to_dict, chunked
|
from ..db_engine import db, Result, Team, model_to_dict, chunked
|
||||||
from ..dependencies import oauth2_scheme, valid_token, PRIVATE_IN_SCHEMA, handle_db_errors
|
from ..dependencies import (
|
||||||
|
oauth2_scheme,
|
||||||
logger = logging.getLogger('discord_app')
|
valid_token,
|
||||||
|
PRIVATE_IN_SCHEMA,
|
||||||
router = APIRouter(
|
handle_db_errors,
|
||||||
prefix='/api/v3/results',
|
|
||||||
tags=['results']
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("discord_app")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/v3/results", tags=["results"])
|
||||||
|
|
||||||
|
|
||||||
class ResultModel(pydantic.BaseModel):
|
class ResultModel(pydantic.BaseModel):
|
||||||
week: int
|
week: int
|
||||||
@ -29,13 +31,18 @@ class ResultList(pydantic.BaseModel):
|
|||||||
results: List[ResultModel]
|
results: List[ResultModel]
|
||||||
|
|
||||||
|
|
||||||
@router.get('')
|
@router.get("")
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def get_results(
|
async def get_results(
|
||||||
season: int, team_abbrev: list = Query(default=None), week_start: Optional[int] = None,
|
season: int,
|
||||||
week_end: Optional[int] = None, game_num: list = Query(default=None),
|
team_abbrev: list = Query(default=None),
|
||||||
away_abbrev: list = Query(default=None), home_abbrev: list = Query(default=None),
|
week_start: Optional[int] = None,
|
||||||
short_output: Optional[bool] = False):
|
week_end: Optional[int] = None,
|
||||||
|
game_num: list = Query(default=None),
|
||||||
|
away_abbrev: list = Query(default=None),
|
||||||
|
home_abbrev: list = Query(default=None),
|
||||||
|
short_output: Optional[bool] = False,
|
||||||
|
):
|
||||||
all_results = Result.select_season(season)
|
all_results = Result.select_season(season)
|
||||||
|
|
||||||
if team_abbrev is not None:
|
if team_abbrev is not None:
|
||||||
@ -68,14 +75,14 @@ async def get_results(
|
|||||||
all_results = all_results.where(Result.week <= week_end)
|
all_results = all_results.where(Result.week <= week_end)
|
||||||
|
|
||||||
return_results = {
|
return_results = {
|
||||||
'count': all_results.count(),
|
"count": all_results.count(),
|
||||||
'results': [model_to_dict(x, recurse=not short_output) for x in all_results]
|
"results": [model_to_dict(x, recurse=not short_output) for x in all_results],
|
||||||
}
|
}
|
||||||
db.close()
|
db.close()
|
||||||
return return_results
|
return return_results
|
||||||
|
|
||||||
|
|
||||||
@router.get('/{result_id}')
|
@router.get("/{result_id}")
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def get_one_result(result_id: int, short_output: Optional[bool] = False):
|
async def get_one_result(result_id: int, short_output: Optional[bool] = False):
|
||||||
this_result = Result.get_or_none(Result.id == result_id)
|
this_result = Result.get_or_none(Result.id == result_id)
|
||||||
@ -87,20 +94,27 @@ async def get_one_result(result_id: int, short_output: Optional[bool] = False):
|
|||||||
return r_result
|
return r_result
|
||||||
|
|
||||||
|
|
||||||
@router.patch('/{result_id}', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.patch("/{result_id}", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def patch_result(
|
async def patch_result(
|
||||||
result_id: int, week_num: Optional[int] = None, game_num: Optional[int] = None,
|
result_id: int,
|
||||||
away_team_id: Optional[int] = None, home_team_id: Optional[int] = None, away_score: Optional[int] = None,
|
week_num: Optional[int] = None,
|
||||||
home_score: Optional[int] = None, season: Optional[int] = None, scorecard_url: Optional[str] = None,
|
game_num: Optional[int] = None,
|
||||||
token: str = Depends(oauth2_scheme)):
|
away_team_id: Optional[int] = None,
|
||||||
|
home_team_id: Optional[int] = None,
|
||||||
|
away_score: Optional[int] = None,
|
||||||
|
home_score: Optional[int] = None,
|
||||||
|
season: Optional[int] = None,
|
||||||
|
scorecard_url: Optional[str] = None,
|
||||||
|
token: str = Depends(oauth2_scheme),
|
||||||
|
):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'patch_player - Bad Token: {token}')
|
logger.warning(f"patch_player - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
this_result = Result.get_or_none(Result.id == result_id)
|
this_result = Result.get_or_none(Result.id == result_id)
|
||||||
if this_result is None:
|
if this_result is None:
|
||||||
raise HTTPException(status_code=404, detail=f'Result ID {result_id} not found')
|
raise HTTPException(status_code=404, detail=f"Result ID {result_id} not found")
|
||||||
|
|
||||||
if week_num is not None:
|
if week_num is not None:
|
||||||
this_result.week = week_num
|
this_result.week = week_num
|
||||||
@ -132,22 +146,39 @@ async def patch_result(
|
|||||||
return r_result
|
return r_result
|
||||||
else:
|
else:
|
||||||
db.close()
|
db.close()
|
||||||
raise HTTPException(status_code=500, detail=f'Unable to patch result {result_id}')
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Unable to patch result {result_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post('', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.post("", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def post_results(result_list: ResultList, token: str = Depends(oauth2_scheme)):
|
async def post_results(result_list: ResultList, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'patch_player - Bad Token: {token}')
|
logger.warning(f"patch_player - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
new_results = []
|
new_results = []
|
||||||
|
|
||||||
|
all_team_ids = list(
|
||||||
|
set(x.awayteam_id for x in result_list.results)
|
||||||
|
| set(x.hometeam_id for x in result_list.results)
|
||||||
|
)
|
||||||
|
found_team_ids = (
|
||||||
|
set(t.id for t in Team.select(Team.id).where(Team.id << all_team_ids))
|
||||||
|
if all_team_ids
|
||||||
|
else set()
|
||||||
|
)
|
||||||
|
|
||||||
for x in result_list.results:
|
for x in result_list.results:
|
||||||
if Team.get_or_none(Team.id == x.awayteam_id) is None:
|
if x.awayteam_id not in found_team_ids:
|
||||||
raise HTTPException(status_code=404, detail=f'Team ID {x.awayteam_id} not found')
|
raise HTTPException(
|
||||||
if Team.get_or_none(Team.id == x.hometeam_id) is None:
|
status_code=404, detail=f"Team ID {x.awayteam_id} not found"
|
||||||
raise HTTPException(status_code=404, detail=f'Team ID {x.hometeam_id} not found')
|
)
|
||||||
|
if x.hometeam_id not in found_team_ids:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"Team ID {x.hometeam_id} not found"
|
||||||
|
)
|
||||||
|
|
||||||
new_results.append(x.dict())
|
new_results.append(x.dict())
|
||||||
|
|
||||||
@ -156,27 +187,27 @@ async def post_results(result_list: ResultList, token: str = Depends(oauth2_sche
|
|||||||
Result.insert_many(batch).on_conflict_ignore().execute()
|
Result.insert_many(batch).on_conflict_ignore().execute()
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
return f'Inserted {len(new_results)} results'
|
return f"Inserted {len(new_results)} results"
|
||||||
|
|
||||||
|
|
||||||
@router.delete('/{result_id}', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.delete("/{result_id}", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def delete_result(result_id: int, token: str = Depends(oauth2_scheme)):
|
async def delete_result(result_id: int, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'delete_result - Bad Token: {token}')
|
logger.warning(f"delete_result - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
this_result = Result.get_or_none(Result.id == result_id)
|
this_result = Result.get_or_none(Result.id == result_id)
|
||||||
if not this_result:
|
if not this_result:
|
||||||
db.close()
|
db.close()
|
||||||
raise HTTPException(status_code=404, detail=f'Result ID {result_id} not found')
|
raise HTTPException(status_code=404, detail=f"Result ID {result_id} not found")
|
||||||
|
|
||||||
count = this_result.delete_instance()
|
count = this_result.delete_instance()
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
if count == 1:
|
if count == 1:
|
||||||
return f'Result {result_id} has been deleted'
|
return f"Result {result_id} has been deleted"
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail=f'Result {result_id} could not be deleted')
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Result {result_id} could not be deleted"
|
||||||
|
)
|
||||||
|
|||||||
@ -4,15 +4,17 @@ import logging
|
|||||||
import pydantic
|
import pydantic
|
||||||
|
|
||||||
from ..db_engine import db, Schedule, Team, model_to_dict, chunked
|
from ..db_engine import db, Schedule, Team, model_to_dict, chunked
|
||||||
from ..dependencies import oauth2_scheme, valid_token, PRIVATE_IN_SCHEMA, handle_db_errors
|
from ..dependencies import (
|
||||||
|
oauth2_scheme,
|
||||||
logger = logging.getLogger('discord_app')
|
valid_token,
|
||||||
|
PRIVATE_IN_SCHEMA,
|
||||||
router = APIRouter(
|
handle_db_errors,
|
||||||
prefix='/api/v3/schedules',
|
|
||||||
tags=['schedules']
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("discord_app")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/v3/schedules", tags=["schedules"])
|
||||||
|
|
||||||
|
|
||||||
class ScheduleModel(pydantic.BaseModel):
|
class ScheduleModel(pydantic.BaseModel):
|
||||||
week: int
|
week: int
|
||||||
@ -26,12 +28,17 @@ class ScheduleList(pydantic.BaseModel):
|
|||||||
schedules: List[ScheduleModel]
|
schedules: List[ScheduleModel]
|
||||||
|
|
||||||
|
|
||||||
@router.get('')
|
@router.get("")
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def get_schedules(
|
async def get_schedules(
|
||||||
season: int, team_abbrev: list = Query(default=None), away_abbrev: list = Query(default=None),
|
season: int,
|
||||||
home_abbrev: list = Query(default=None), week_start: Optional[int] = None, week_end: Optional[int] = None,
|
team_abbrev: list = Query(default=None),
|
||||||
short_output: Optional[bool] = True):
|
away_abbrev: list = Query(default=None),
|
||||||
|
home_abbrev: list = Query(default=None),
|
||||||
|
week_start: Optional[int] = None,
|
||||||
|
week_end: Optional[int] = None,
|
||||||
|
short_output: Optional[bool] = True,
|
||||||
|
):
|
||||||
all_sched = Schedule.select_season(season)
|
all_sched = Schedule.select_season(season)
|
||||||
|
|
||||||
if team_abbrev is not None:
|
if team_abbrev is not None:
|
||||||
@ -63,14 +70,14 @@ async def get_schedules(
|
|||||||
all_sched = all_sched.order_by(Schedule.id)
|
all_sched = all_sched.order_by(Schedule.id)
|
||||||
|
|
||||||
return_sched = {
|
return_sched = {
|
||||||
'count': all_sched.count(),
|
"count": all_sched.count(),
|
||||||
'schedules': [model_to_dict(x, recurse=not short_output) for x in all_sched]
|
"schedules": [model_to_dict(x, recurse=not short_output) for x in all_sched],
|
||||||
}
|
}
|
||||||
db.close()
|
db.close()
|
||||||
return return_sched
|
return return_sched
|
||||||
|
|
||||||
|
|
||||||
@router.get('/{schedule_id}')
|
@router.get("/{schedule_id}")
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def get_one_schedule(schedule_id: int):
|
async def get_one_schedule(schedule_id: int):
|
||||||
this_sched = Schedule.get_or_none(Schedule.id == schedule_id)
|
this_sched = Schedule.get_or_none(Schedule.id == schedule_id)
|
||||||
@ -82,19 +89,26 @@ async def get_one_schedule(schedule_id: int):
|
|||||||
return r_sched
|
return r_sched
|
||||||
|
|
||||||
|
|
||||||
@router.patch('/{schedule_id}', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.patch("/{schedule_id}", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def patch_schedule(
|
async def patch_schedule(
|
||||||
schedule_id: int, week: list = Query(default=None), awayteam_id: Optional[int] = None,
|
schedule_id: int,
|
||||||
hometeam_id: Optional[int] = None, gamecount: Optional[int] = None, season: Optional[int] = None,
|
week: list = Query(default=None),
|
||||||
token: str = Depends(oauth2_scheme)):
|
awayteam_id: Optional[int] = None,
|
||||||
|
hometeam_id: Optional[int] = None,
|
||||||
|
gamecount: Optional[int] = None,
|
||||||
|
season: Optional[int] = None,
|
||||||
|
token: str = Depends(oauth2_scheme),
|
||||||
|
):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'patch_schedule - Bad Token: {token}')
|
logger.warning(f"patch_schedule - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
this_sched = Schedule.get_or_none(Schedule.id == schedule_id)
|
this_sched = Schedule.get_or_none(Schedule.id == schedule_id)
|
||||||
if this_sched is None:
|
if this_sched is None:
|
||||||
raise HTTPException(status_code=404, detail=f'Schedule ID {schedule_id} not found')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"Schedule ID {schedule_id} not found"
|
||||||
|
)
|
||||||
|
|
||||||
if week is not None:
|
if week is not None:
|
||||||
this_sched.week = week
|
this_sched.week = week
|
||||||
@ -117,22 +131,39 @@ async def patch_schedule(
|
|||||||
return r_sched
|
return r_sched
|
||||||
else:
|
else:
|
||||||
db.close()
|
db.close()
|
||||||
raise HTTPException(status_code=500, detail=f'Unable to patch schedule {schedule_id}')
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Unable to patch schedule {schedule_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post('', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.post("", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def post_schedules(sched_list: ScheduleList, token: str = Depends(oauth2_scheme)):
|
async def post_schedules(sched_list: ScheduleList, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'post_schedules - Bad Token: {token}')
|
logger.warning(f"post_schedules - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
new_sched = []
|
new_sched = []
|
||||||
|
|
||||||
|
all_team_ids = list(
|
||||||
|
set(x.awayteam_id for x in sched_list.schedules)
|
||||||
|
| set(x.hometeam_id for x in sched_list.schedules)
|
||||||
|
)
|
||||||
|
found_team_ids = (
|
||||||
|
set(t.id for t in Team.select(Team.id).where(Team.id << all_team_ids))
|
||||||
|
if all_team_ids
|
||||||
|
else set()
|
||||||
|
)
|
||||||
|
|
||||||
for x in sched_list.schedules:
|
for x in sched_list.schedules:
|
||||||
if Team.get_or_none(Team.id == x.awayteam_id) is None:
|
if x.awayteam_id not in found_team_ids:
|
||||||
raise HTTPException(status_code=404, detail=f'Team ID {x.awayteam_id} not found')
|
raise HTTPException(
|
||||||
if Team.get_or_none(Team.id == x.hometeam_id) is None:
|
status_code=404, detail=f"Team ID {x.awayteam_id} not found"
|
||||||
raise HTTPException(status_code=404, detail=f'Team ID {x.hometeam_id} not found')
|
)
|
||||||
|
if x.hometeam_id not in found_team_ids:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"Team ID {x.hometeam_id} not found"
|
||||||
|
)
|
||||||
|
|
||||||
new_sched.append(x.dict())
|
new_sched.append(x.dict())
|
||||||
|
|
||||||
@ -141,24 +172,28 @@ async def post_schedules(sched_list: ScheduleList, token: str = Depends(oauth2_s
|
|||||||
Schedule.insert_many(batch).on_conflict_ignore().execute()
|
Schedule.insert_many(batch).on_conflict_ignore().execute()
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
return f'Inserted {len(new_sched)} schedules'
|
return f"Inserted {len(new_sched)} schedules"
|
||||||
|
|
||||||
|
|
||||||
@router.delete('/{schedule_id}', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.delete("/{schedule_id}", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def delete_schedule(schedule_id: int, token: str = Depends(oauth2_scheme)):
|
async def delete_schedule(schedule_id: int, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'delete_schedule - Bad Token: {token}')
|
logger.warning(f"delete_schedule - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
this_sched = Schedule.get_or_none(Schedule.id == schedule_id)
|
this_sched = Schedule.get_or_none(Schedule.id == schedule_id)
|
||||||
if this_sched is None:
|
if this_sched is None:
|
||||||
raise HTTPException(status_code=404, detail=f'Schedule ID {schedule_id} not found')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"Schedule ID {schedule_id} not found"
|
||||||
|
)
|
||||||
|
|
||||||
count = this_sched.delete_instance()
|
count = this_sched.delete_instance()
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
if count == 1:
|
if count == 1:
|
||||||
return f'Schedule {this_sched} has been deleted'
|
return f"Schedule {this_sched} has been deleted"
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail=f'Schedule {this_sched} could not be deleted')
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Schedule {this_sched} could not be deleted"
|
||||||
|
)
|
||||||
|
|||||||
@ -5,15 +5,17 @@ import logging
|
|||||||
import pydantic
|
import pydantic
|
||||||
|
|
||||||
from ..db_engine import db, Transaction, Team, Player, model_to_dict, chunked, fn
|
from ..db_engine import db, Transaction, Team, Player, model_to_dict, chunked, fn
|
||||||
from ..dependencies import oauth2_scheme, valid_token, PRIVATE_IN_SCHEMA, handle_db_errors
|
from ..dependencies import (
|
||||||
|
oauth2_scheme,
|
||||||
logger = logging.getLogger('discord_app')
|
valid_token,
|
||||||
|
PRIVATE_IN_SCHEMA,
|
||||||
router = APIRouter(
|
handle_db_errors,
|
||||||
prefix='/api/v3/transactions',
|
|
||||||
tags=['transactions']
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("discord_app")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/v3/transactions", tags=["transactions"])
|
||||||
|
|
||||||
|
|
||||||
class TransactionModel(pydantic.BaseModel):
|
class TransactionModel(pydantic.BaseModel):
|
||||||
week: int
|
week: int
|
||||||
@ -31,13 +33,21 @@ class TransactionList(pydantic.BaseModel):
|
|||||||
moves: List[TransactionModel]
|
moves: List[TransactionModel]
|
||||||
|
|
||||||
|
|
||||||
@router.get('')
|
@router.get("")
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def get_transactions(
|
async def get_transactions(
|
||||||
season, team_abbrev: list = Query(default=None), week_start: Optional[int] = 0,
|
season,
|
||||||
week_end: Optional[int] = None, cancelled: Optional[bool] = None, frozen: Optional[bool] = None,
|
team_abbrev: list = Query(default=None),
|
||||||
player_name: list = Query(default=None), player_id: list = Query(default=None), move_id: Optional[str] = None,
|
week_start: Optional[int] = 0,
|
||||||
is_trade: Optional[bool] = None, short_output: Optional[bool] = False):
|
week_end: Optional[int] = None,
|
||||||
|
cancelled: Optional[bool] = None,
|
||||||
|
frozen: Optional[bool] = None,
|
||||||
|
player_name: list = Query(default=None),
|
||||||
|
player_id: list = Query(default=None),
|
||||||
|
move_id: Optional[str] = None,
|
||||||
|
is_trade: Optional[bool] = None,
|
||||||
|
short_output: Optional[bool] = False,
|
||||||
|
):
|
||||||
if season:
|
if season:
|
||||||
transactions = Transaction.select_season(season)
|
transactions = Transaction.select_season(season)
|
||||||
else:
|
else:
|
||||||
@ -75,31 +85,39 @@ async def get_transactions(
|
|||||||
transactions = transactions.where(Transaction.frozen == 0)
|
transactions = transactions.where(Transaction.frozen == 0)
|
||||||
|
|
||||||
if is_trade is not None:
|
if is_trade is not None:
|
||||||
raise HTTPException(status_code=501, detail='The is_trade parameter is not implemented, yet')
|
raise HTTPException(
|
||||||
|
status_code=501, detail="The is_trade parameter is not implemented, yet"
|
||||||
|
)
|
||||||
|
|
||||||
transactions = transactions.order_by(-Transaction.week, Transaction.moveid)
|
transactions = transactions.order_by(-Transaction.week, Transaction.moveid)
|
||||||
|
|
||||||
return_trans = {
|
return_trans = {
|
||||||
'count': transactions.count(),
|
"count": transactions.count(),
|
||||||
'transactions': [model_to_dict(x, recurse=not short_output) for x in transactions]
|
"transactions": [
|
||||||
|
model_to_dict(x, recurse=not short_output) for x in transactions
|
||||||
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
db.close()
|
db.close()
|
||||||
return return_trans
|
return return_trans
|
||||||
|
|
||||||
|
|
||||||
@router.patch('/{move_id}', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.patch("/{move_id}", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def patch_transactions(
|
async def patch_transactions(
|
||||||
move_id, token: str = Depends(oauth2_scheme), frozen: Optional[bool] = None, cancelled: Optional[bool] = None):
|
move_id,
|
||||||
|
token: str = Depends(oauth2_scheme),
|
||||||
|
frozen: Optional[bool] = None,
|
||||||
|
cancelled: Optional[bool] = None,
|
||||||
|
):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'patch_transactions - Bad Token: {token}')
|
logger.warning(f"patch_transactions - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
these_moves = Transaction.select().where(Transaction.moveid == move_id)
|
these_moves = Transaction.select().where(Transaction.moveid == move_id)
|
||||||
if these_moves.count() == 0:
|
if these_moves.count() == 0:
|
||||||
db.close()
|
db.close()
|
||||||
raise HTTPException(status_code=404, detail=f'Move ID {move_id} not found')
|
raise HTTPException(status_code=404, detail=f"Move ID {move_id} not found")
|
||||||
|
|
||||||
if frozen is not None:
|
if frozen is not None:
|
||||||
for x in these_moves:
|
for x in these_moves:
|
||||||
@ -111,25 +129,48 @@ async def patch_transactions(
|
|||||||
x.save()
|
x.save()
|
||||||
|
|
||||||
db.close()
|
db.close()
|
||||||
return f'Updated {these_moves.count()} transactions'
|
return f"Updated {these_moves.count()} transactions"
|
||||||
|
|
||||||
|
|
||||||
@router.post('', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.post("", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def post_transactions(moves: TransactionList, token: str = Depends(oauth2_scheme)):
|
async def post_transactions(
|
||||||
|
moves: TransactionList, token: str = Depends(oauth2_scheme)
|
||||||
|
):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'post_transactions - Bad Token: {token}')
|
logger.warning(f"post_transactions - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
all_moves = []
|
all_moves = []
|
||||||
|
|
||||||
|
all_team_ids = list(
|
||||||
|
set(x.oldteam_id for x in moves.moves) | set(x.newteam_id for x in moves.moves)
|
||||||
|
)
|
||||||
|
all_player_ids = list(set(x.player_id for x in moves.moves))
|
||||||
|
found_team_ids = (
|
||||||
|
set(t.id for t in Team.select(Team.id).where(Team.id << all_team_ids))
|
||||||
|
if all_team_ids
|
||||||
|
else set()
|
||||||
|
)
|
||||||
|
found_player_ids = (
|
||||||
|
set(p.id for p in Player.select(Player.id).where(Player.id << all_player_ids))
|
||||||
|
if all_player_ids
|
||||||
|
else set()
|
||||||
|
)
|
||||||
|
|
||||||
for x in moves.moves:
|
for x in moves.moves:
|
||||||
if Team.get_or_none(Team.id == x.oldteam_id) is None:
|
if x.oldteam_id not in found_team_ids:
|
||||||
raise HTTPException(status_code=404, detail=f'Team ID {x.oldteam_id} not found')
|
raise HTTPException(
|
||||||
if Team.get_or_none(Team.id == x.newteam_id) is None:
|
status_code=404, detail=f"Team ID {x.oldteam_id} not found"
|
||||||
raise HTTPException(status_code=404, detail=f'Team ID {x.newteam_id} not found')
|
)
|
||||||
if Player.get_or_none(Player.id == x.player_id) is None:
|
if x.newteam_id not in found_team_ids:
|
||||||
raise HTTPException(status_code=404, detail=f'Player ID {x.player_id} not found')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"Team ID {x.newteam_id} not found"
|
||||||
|
)
|
||||||
|
if x.player_id not in found_player_ids:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"Player ID {x.player_id} not found"
|
||||||
|
)
|
||||||
|
|
||||||
all_moves.append(x.dict())
|
all_moves.append(x.dict())
|
||||||
|
|
||||||
@ -138,22 +179,25 @@ async def post_transactions(moves: TransactionList, token: str = Depends(oauth2_
|
|||||||
Transaction.insert_many(batch).on_conflict_ignore().execute()
|
Transaction.insert_many(batch).on_conflict_ignore().execute()
|
||||||
|
|
||||||
db.close()
|
db.close()
|
||||||
return f'{len(all_moves)} transactions have been added'
|
return f"{len(all_moves)} transactions have been added"
|
||||||
|
|
||||||
|
|
||||||
@router.delete('/{move_id}', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.delete("/{move_id}", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def delete_transactions(move_id, token: str = Depends(oauth2_scheme)):
|
async def delete_transactions(move_id, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'delete_transactions - Bad Token: {token}')
|
logger.warning(f"delete_transactions - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
delete_query = Transaction.delete().where(Transaction.moveid == move_id)
|
delete_query = Transaction.delete().where(Transaction.moveid == move_id)
|
||||||
|
|
||||||
count = delete_query.execute()
|
count = delete_query.execute()
|
||||||
db.close()
|
db.close()
|
||||||
if count > 0:
|
if count > 0:
|
||||||
return f'Removed {count} transactions'
|
return f"Removed {count} transactions"
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=418, detail=f'Well slap my ass and call me a teapot; '
|
raise HTTPException(
|
||||||
f'I did not delete any records')
|
status_code=418,
|
||||||
|
detail=f"Well slap my ass and call me a teapot; "
|
||||||
|
f"I did not delete any records",
|
||||||
|
)
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user