from fastapi import APIRouter, Depends, HTTPException, Query from typing import List, Optional import logging import pydantic from ..db_engine import db, Standings, Team, Division, model_to_dict, chunked, fn from ..dependencies import oauth2_scheme, valid_token, LOG_DATA logging.basicConfig( filename=LOG_DATA['filename'], format=LOG_DATA['format'], level=LOG_DATA['log_level'] ) router = APIRouter( prefix='/api/v3/standings', tags=['standings'] ) @router.get('') async def get_standings( season: int, team_id: list = Query(default=None), league_abbrev: Optional[str] = None, division_abbrev: Optional[str] = None, short_output: Optional[bool] = False): standings = Standings.select_season(season) # if standings.count() == 0: # db.close() # raise HTTPException(status_code=404, detail=f'No output for season {season}') if team_id is not None: t_query = Team.select().where(Team.id << team_id) standings = standings.where(Standings.team << t_query) if league_abbrev is not None: l_query = Division.select().where(fn.Lower(Division.league_abbrev) == league_abbrev.lower()) standings = standings.where(Standings.team.division << l_query) if division_abbrev is not None: d_query = Division.select().where(fn.Lower(Division.division_abbrev) == division_abbrev.lower()) standings = standings.where(Standings.team.division << d_query) def win_pct(this_team_stan): if this_team_stan.wins + this_team_stan.losses == 0: return 0 else: return (this_team_stan.wins / (this_team_stan.wins + this_team_stan.losses)) + \ (this_team_stan.run_diff * .000001) div_teams = [x for x in standings] div_teams.sort(key=lambda team: win_pct(team), reverse=True) return_standings = { 'count': len(div_teams), 'standings': [model_to_dict(x, recurse=not short_output) for x in div_teams] } db.close() return return_standings @router.get('/team/{team_id}') async def get_team_standings(team_id: int): this_stan = Standings.get_or_none(Standings.team_id == team_id) if this_stan is None: raise HTTPException(status_code=404, detail=f'No standings found for team id {team_id}') return model_to_dict(this_stan) @router.patch('/{stan_id}') async def patch_standings( stan_id, wins: Optional[int] = None, losses: Optional[int] = None, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'patch_standings - Bad Token: {token}') raise HTTPException(status_code=401, detail='Unauthorized') try: this_stan = Standings.get_by_id(stan_id) except Exception as e: db.close() raise HTTPException(status_code=404, detail=f'No team found with id {stan_id}') if wins: this_stan.wins = wins if losses: this_stan.losses = losses this_stan.save() db.close() return model_to_dict(this_stan) @router.post('/s{season}/recalculate') async def recalculate_standings(season: int, token: str = Depends(oauth2_scheme)): if not valid_token(token): logging.warning(f'recalculate_standings - Bad Token: {token}') raise HTTPException(status_code=401, detail='Unauthorized') code = Standings.recalculate(season) db.close() if code == 69: HTTPException(status_code=500, detail=f'Error recreating Standings rows') raise HTTPException(status_code=200, detail=f'Just recalculated standings for season {season}')