fix: raise HTTPException in recalculate_standings on failure (#23)
All checks were successful
Build Docker Image / build (pull_request) Successful in 2m3s
All checks were successful
Build Docker Image / build (pull_request) Successful in 2m3s
The HTTPException was constructed but never raised, causing the endpoint to always return 200 even when Standings.recalculate() signalled an error. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
8143913aa2
commit
a8e1aecb40
@ -4,21 +4,27 @@ import logging
|
|||||||
import pydantic
|
import pydantic
|
||||||
|
|
||||||
from ..db_engine import db, Standings, Team, Division, model_to_dict, chunked, fn
|
from ..db_engine import db, Standings, Team, Division, 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/standings',
|
|
||||||
tags=['standings']
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("discord_app")
|
||||||
|
|
||||||
@router.get('')
|
router = APIRouter(prefix="/api/v3/standings", tags=["standings"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def get_standings(
|
async def get_standings(
|
||||||
season: int, team_id: list = Query(default=None), league_abbrev: Optional[str] = None,
|
season: int,
|
||||||
division_abbrev: Optional[str] = None, short_output: Optional[bool] = False):
|
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)
|
standings = Standings.select_season(season)
|
||||||
|
|
||||||
# if standings.count() == 0:
|
# if standings.count() == 0:
|
||||||
@ -30,55 +36,66 @@ async def get_standings(
|
|||||||
standings = standings.where(Standings.team << t_query)
|
standings = standings.where(Standings.team << t_query)
|
||||||
|
|
||||||
if league_abbrev is not None:
|
if league_abbrev is not None:
|
||||||
l_query = Division.select().where(fn.Lower(Division.league_abbrev) == league_abbrev.lower())
|
l_query = Division.select().where(
|
||||||
|
fn.Lower(Division.league_abbrev) == league_abbrev.lower()
|
||||||
|
)
|
||||||
standings = standings.where(Standings.team.division << l_query)
|
standings = standings.where(Standings.team.division << l_query)
|
||||||
|
|
||||||
if division_abbrev is not None:
|
if division_abbrev is not None:
|
||||||
d_query = Division.select().where(fn.Lower(Division.division_abbrev) == division_abbrev.lower())
|
d_query = Division.select().where(
|
||||||
|
fn.Lower(Division.division_abbrev) == division_abbrev.lower()
|
||||||
|
)
|
||||||
standings = standings.where(Standings.team.division << d_query)
|
standings = standings.where(Standings.team.division << d_query)
|
||||||
|
|
||||||
def win_pct(this_team_stan):
|
def win_pct(this_team_stan):
|
||||||
if this_team_stan.wins + this_team_stan.losses == 0:
|
if this_team_stan.wins + this_team_stan.losses == 0:
|
||||||
return 0
|
return 0
|
||||||
else:
|
else:
|
||||||
return (this_team_stan.wins / (this_team_stan.wins + this_team_stan.losses)) + \
|
return (
|
||||||
(this_team_stan.run_diff * .000001)
|
this_team_stan.wins / (this_team_stan.wins + this_team_stan.losses)
|
||||||
|
) + (this_team_stan.run_diff * 0.000001)
|
||||||
|
|
||||||
div_teams = [x for x in standings]
|
div_teams = [x for x in standings]
|
||||||
div_teams.sort(key=lambda team: win_pct(team), reverse=True)
|
div_teams.sort(key=lambda team: win_pct(team), reverse=True)
|
||||||
|
|
||||||
return_standings = {
|
return_standings = {
|
||||||
'count': len(div_teams),
|
"count": len(div_teams),
|
||||||
'standings': [model_to_dict(x, recurse=not short_output) for x in div_teams]
|
"standings": [model_to_dict(x, recurse=not short_output) for x in div_teams],
|
||||||
}
|
}
|
||||||
|
|
||||||
db.close()
|
db.close()
|
||||||
return return_standings
|
return return_standings
|
||||||
|
|
||||||
|
|
||||||
@router.get('/team/{team_id}')
|
@router.get("/team/{team_id}")
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def get_team_standings(team_id: int):
|
async def get_team_standings(team_id: int):
|
||||||
this_stan = Standings.get_or_none(Standings.team_id == team_id)
|
this_stan = Standings.get_or_none(Standings.team_id == team_id)
|
||||||
if this_stan is None:
|
if this_stan is None:
|
||||||
raise HTTPException(status_code=404, detail=f'No standings found for team id {team_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No standings found for team id {team_id}"
|
||||||
|
)
|
||||||
|
|
||||||
return model_to_dict(this_stan)
|
return model_to_dict(this_stan)
|
||||||
|
|
||||||
|
|
||||||
@router.patch('/{stan_id}', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.patch("/{stan_id}", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def patch_standings(
|
async def patch_standings(
|
||||||
stan_id, wins: Optional[int] = None, losses: Optional[int] = None, token: str = Depends(oauth2_scheme)):
|
stan_id,
|
||||||
|
wins: Optional[int] = None,
|
||||||
|
losses: Optional[int] = None,
|
||||||
|
token: str = Depends(oauth2_scheme),
|
||||||
|
):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'patch_standings - Bad Token: {token}')
|
logger.warning(f"patch_standings - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
this_stan = Standings.get_by_id(stan_id)
|
this_stan = Standings.get_by_id(stan_id)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
db.close()
|
db.close()
|
||||||
raise HTTPException(status_code=404, detail=f'No team found with id {stan_id}')
|
raise HTTPException(status_code=404, detail=f"No team found with id {stan_id}")
|
||||||
|
|
||||||
if wins:
|
if wins:
|
||||||
this_stan.wins = wins
|
this_stan.wins = wins
|
||||||
@ -91,35 +108,35 @@ async def patch_standings(
|
|||||||
return model_to_dict(this_stan)
|
return model_to_dict(this_stan)
|
||||||
|
|
||||||
|
|
||||||
@router.post('/s{season}/new', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.post("/s{season}/new", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def post_standings(season: int, token: str = Depends(oauth2_scheme)):
|
async def post_standings(season: int, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'post_standings - Bad Token: {token}')
|
logger.warning(f"post_standings - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
new_teams = []
|
new_teams = []
|
||||||
all_teams = Team.select().where(Team.season == season)
|
all_teams = Team.select().where(Team.season == season)
|
||||||
for x in all_teams:
|
for x in all_teams:
|
||||||
new_teams.append(Standings({'team_id': x.id}))
|
new_teams.append(Standings({"team_id": x.id}))
|
||||||
|
|
||||||
with db.atomic():
|
with db.atomic():
|
||||||
for batch in chunked(new_teams, 16):
|
for batch in chunked(new_teams, 16):
|
||||||
Standings.insert_many(batch).on_conflict_ignore().execute()
|
Standings.insert_many(batch).on_conflict_ignore().execute()
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
return f'Inserted {len(new_teams)} standings'
|
return f"Inserted {len(new_teams)} standings"
|
||||||
|
|
||||||
|
|
||||||
@router.post('/s{season}/recalculate', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.post("/s{season}/recalculate", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
@handle_db_errors
|
@handle_db_errors
|
||||||
async def recalculate_standings(season: int, token: str = Depends(oauth2_scheme)):
|
async def recalculate_standings(season: int, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logger.warning(f'recalculate_standings - Bad Token: {token}')
|
logger.warning(f"recalculate_standings - Bad Token: {token}")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
code = Standings.recalculate(season)
|
code = Standings.recalculate(season)
|
||||||
db.close()
|
db.close()
|
||||||
if code == 69:
|
if code == 69:
|
||||||
HTTPException(status_code=500, detail=f'Error recreating Standings rows')
|
raise HTTPException(status_code=500, detail=f"Error recreating Standings rows")
|
||||||
return f'Just recalculated standings for season {season}'
|
return f"Just recalculated standings for season {season}"
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user