Merge branch 'main' into issue/139-feat-add-limit-pagination-to-rewards-endpoint
This commit is contained in:
commit
23b95f2d3d
@ -8,16 +8,13 @@ from ..db_engine import Award, model_to_dict, DoesNotExist
|
|||||||
from ..dependencies import oauth2_scheme, valid_token, PRIVATE_IN_SCHEMA
|
from ..dependencies import oauth2_scheme, valid_token, PRIVATE_IN_SCHEMA
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter(
|
router = APIRouter(prefix="/api/v2/awards", tags=["awards"])
|
||||||
prefix='/api/v2/awards',
|
|
||||||
tags=['awards']
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class AwardModel(pydantic.BaseModel):
|
class AwardModel(pydantic.BaseModel):
|
||||||
name: str
|
name: str
|
||||||
season: int
|
season: int
|
||||||
timing: str = 'In-Season'
|
timing: str = "In-Season"
|
||||||
card_id: Optional[int] = None
|
card_id: Optional[int] = None
|
||||||
team_id: Optional[int] = None
|
team_id: Optional[int] = None
|
||||||
image: Optional[str] = None
|
image: Optional[str] = None
|
||||||
@ -28,15 +25,21 @@ class AwardReturnList(pydantic.BaseModel):
|
|||||||
awards: list[AwardModel]
|
awards: list[AwardModel]
|
||||||
|
|
||||||
|
|
||||||
@router.get('')
|
@router.get("")
|
||||||
async def get_awards(
|
async def get_awards(
|
||||||
name: Optional[str] = None, season: Optional[int] = None, timing: Optional[str] = None,
|
name: Optional[str] = None,
|
||||||
card_id: Optional[int] = None, team_id: Optional[int] = None, image: Optional[str] = None,
|
season: Optional[int] = None,
|
||||||
csv: Optional[bool] = None):
|
timing: Optional[str] = None,
|
||||||
|
card_id: Optional[int] = None,
|
||||||
|
team_id: Optional[int] = None,
|
||||||
|
image: Optional[str] = None,
|
||||||
|
csv: Optional[bool] = None,
|
||||||
|
limit: int = 100,
|
||||||
|
):
|
||||||
all_awards = Award.select().order_by(Award.id)
|
all_awards = Award.select().order_by(Award.id)
|
||||||
|
|
||||||
if all_awards.count() == 0:
|
if all_awards.count() == 0:
|
||||||
raise HTTPException(status_code=404, detail=f'There are no awards to filter')
|
raise HTTPException(status_code=404, detail="There are no awards to filter")
|
||||||
|
|
||||||
if name is not None:
|
if name is not None:
|
||||||
all_awards = all_awards.where(Award.name == name)
|
all_awards = all_awards.where(Award.name == name)
|
||||||
@ -51,53 +54,73 @@ async def get_awards(
|
|||||||
if image is not None:
|
if image is not None:
|
||||||
all_awards = all_awards.where(Award.image == image)
|
all_awards = all_awards.where(Award.image == image)
|
||||||
|
|
||||||
|
limit = max(0, min(limit, 500))
|
||||||
|
all_awards = all_awards.limit(limit)
|
||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
data_list = [['id', 'name', 'season', 'timing', 'card', 'team', 'image']]
|
data_list = [["id", "name", "season", "timing", "card", "team", "image"]]
|
||||||
for line in all_awards:
|
for line in all_awards:
|
||||||
data_list.append([
|
data_list.append(
|
||||||
line.id, line.name, line.season, line.timing, line.card, line.team, line.image
|
[
|
||||||
])
|
line.id,
|
||||||
|
line.name,
|
||||||
|
line.season,
|
||||||
|
line.timing,
|
||||||
|
line.card,
|
||||||
|
line.team,
|
||||||
|
line.image,
|
||||||
|
]
|
||||||
|
)
|
||||||
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
||||||
|
|
||||||
return Response(content=return_val, media_type='text/csv')
|
return Response(content=return_val, media_type="text/csv")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return_val = {'count': all_awards.count(), 'awards': []}
|
return_val = {"count": all_awards.count(), "awards": []}
|
||||||
for x in all_awards:
|
for x in all_awards:
|
||||||
return_val['awards'].append(model_to_dict(x))
|
return_val["awards"].append(model_to_dict(x))
|
||||||
|
|
||||||
return return_val
|
return return_val
|
||||||
|
|
||||||
|
|
||||||
@router.get('/{award_id}')
|
@router.get("/{award_id}")
|
||||||
async def get_one_award(award_id, csv: Optional[bool] = None):
|
async def get_one_award(award_id, csv: Optional[bool] = None):
|
||||||
try:
|
try:
|
||||||
this_award = Award.get_by_id(award_id)
|
this_award = Award.get_by_id(award_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No award found with id {award_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No award found with id {award_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
data_list = [
|
data_list = [
|
||||||
['id', 'name', 'season', 'timing', 'card', 'team', 'image'],
|
["id", "name", "season", "timing", "card", "team", "image"],
|
||||||
[this_award.id, this_award.name, this_award.season, this_award.timing, this_award.card,
|
[
|
||||||
this_award.team, this_award.image]
|
this_award.id,
|
||||||
|
this_award.name,
|
||||||
|
this_award.season,
|
||||||
|
this_award.timing,
|
||||||
|
this_award.card,
|
||||||
|
this_award.team,
|
||||||
|
this_award.image,
|
||||||
|
],
|
||||||
]
|
]
|
||||||
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
||||||
|
|
||||||
return Response(content=return_val, media_type='text/csv')
|
return Response(content=return_val, media_type="text/csv")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return_val = model_to_dict(this_award)
|
return_val = model_to_dict(this_award)
|
||||||
return return_val
|
return return_val
|
||||||
|
|
||||||
|
|
||||||
@router.post('', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.post("", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
async def post_awards(award: AwardModel, token: str = Depends(oauth2_scheme)):
|
async def post_awards(award: AwardModel, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('Bad Token: [REDACTED]')
|
logging.warning("Bad Token: [REDACTED]")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=401,
|
status_code=401,
|
||||||
detail='You are not authorized to post awards. This event has been logged.'
|
detail="You are not authorized to post awards. This event has been logged.",
|
||||||
)
|
)
|
||||||
|
|
||||||
this_award = Award(
|
this_award = Award(
|
||||||
@ -106,7 +129,7 @@ async def post_awards(award: AwardModel, token: str = Depends(oauth2_scheme)):
|
|||||||
timing=award.season,
|
timing=award.season,
|
||||||
card_id=award.card_id,
|
card_id=award.card_id,
|
||||||
team_id=award.team_id,
|
team_id=award.team_id,
|
||||||
image=award.image
|
image=award.image,
|
||||||
)
|
)
|
||||||
|
|
||||||
saved = this_award.save()
|
saved = this_award.save()
|
||||||
@ -116,28 +139,30 @@ async def post_awards(award: AwardModel, token: str = Depends(oauth2_scheme)):
|
|||||||
else:
|
else:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=418,
|
status_code=418,
|
||||||
detail='Well slap my ass and call me a teapot; I could not save that roster'
|
detail="Well slap my ass and call me a teapot; I could not save that roster",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.delete('/{award_id}', include_in_schema=PRIVATE_IN_SCHEMA)
|
@router.delete("/{award_id}", include_in_schema=PRIVATE_IN_SCHEMA)
|
||||||
async def delete_award(award_id, token: str = Depends(oauth2_scheme)):
|
async def delete_award(award_id, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('Bad Token: [REDACTED]')
|
logging.warning("Bad Token: [REDACTED]")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=401,
|
status_code=401,
|
||||||
detail='You are not authorized to delete awards. This event has been logged.'
|
detail="You are not authorized to delete awards. This event has been logged.",
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
this_award = Award.get_by_id(award_id)
|
this_award = Award.get_by_id(award_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No award found with id {award_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No award found with id {award_id}"
|
||||||
|
)
|
||||||
|
|
||||||
count = this_award.delete_instance()
|
count = this_award.delete_instance()
|
||||||
|
|
||||||
if count == 1:
|
if count == 1:
|
||||||
raise HTTPException(status_code=200, detail=f'Award {award_id} has been deleted')
|
raise HTTPException(
|
||||||
|
status_code=200, detail=f"Award {award_id} has been deleted"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail=f'Award {award_id} was not deleted')
|
raise HTTPException(status_code=500, detail=f"Award {award_id} was not deleted")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -8,10 +8,7 @@ from ..db_engine import GameRewards, model_to_dict, DoesNotExist
|
|||||||
from ..dependencies import oauth2_scheme, valid_token
|
from ..dependencies import oauth2_scheme, valid_token
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter(
|
router = APIRouter(prefix="/api/v2/gamerewards", tags=["gamerewards"])
|
||||||
prefix='/api/v2/gamerewards',
|
|
||||||
tags=['gamerewards']
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class GameRewardModel(pydantic.BaseModel):
|
class GameRewardModel(pydantic.BaseModel):
|
||||||
@ -21,10 +18,15 @@ class GameRewardModel(pydantic.BaseModel):
|
|||||||
money: Optional[int] = None
|
money: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
@router.get('')
|
@router.get("")
|
||||||
async def v1_gamerewards_get(
|
async def v1_gamerewards_get(
|
||||||
name: Optional[str] = None, pack_type_id: Optional[int] = None, player_id: Optional[int] = None,
|
name: Optional[str] = None,
|
||||||
money: Optional[int] = None, csv: Optional[bool] = None):
|
pack_type_id: Optional[int] = None,
|
||||||
|
player_id: Optional[int] = None,
|
||||||
|
money: Optional[int] = None,
|
||||||
|
csv: Optional[bool] = None,
|
||||||
|
limit: int = 100,
|
||||||
|
):
|
||||||
all_rewards = GameRewards.select().order_by(GameRewards.id)
|
all_rewards = GameRewards.select().order_by(GameRewards.id)
|
||||||
|
|
||||||
# if all_rewards.count() == 0:
|
# if all_rewards.count() == 0:
|
||||||
@ -40,61 +42,76 @@ async def v1_gamerewards_get(
|
|||||||
if money is not None:
|
if money is not None:
|
||||||
all_rewards = all_rewards.where(GameRewards.money == money)
|
all_rewards = all_rewards.where(GameRewards.money == money)
|
||||||
|
|
||||||
|
limit = max(0, min(limit, 500))
|
||||||
|
all_rewards = all_rewards.limit(limit)
|
||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
data_list = [['id', 'pack_type_id', 'player_id', 'money']]
|
data_list = [["id", "pack_type_id", "player_id", "money"]]
|
||||||
for line in all_rewards:
|
for line in all_rewards:
|
||||||
data_list.append([
|
data_list.append(
|
||||||
line.id, line.pack_type_id if line.pack_type else None, line.player_id if line.player else None,
|
[
|
||||||
line.money
|
line.id,
|
||||||
])
|
line.pack_type_id if line.pack_type else None,
|
||||||
|
line.player_id if line.player else None,
|
||||||
|
line.money,
|
||||||
|
]
|
||||||
|
)
|
||||||
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
||||||
|
|
||||||
return Response(content=return_val, media_type='text/csv')
|
return Response(content=return_val, media_type="text/csv")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return_val = {'count': all_rewards.count(), 'gamerewards': []}
|
return_val = {"count": all_rewards.count(), "gamerewards": []}
|
||||||
for x in all_rewards:
|
for x in all_rewards:
|
||||||
return_val['gamerewards'].append(model_to_dict(x))
|
return_val["gamerewards"].append(model_to_dict(x))
|
||||||
|
|
||||||
return return_val
|
return return_val
|
||||||
|
|
||||||
|
|
||||||
@router.get('/{gameaward_id}')
|
@router.get("/{gameaward_id}")
|
||||||
async def v1_gamerewards_get_one(gamereward_id, csv: Optional[bool] = None):
|
async def v1_gamerewards_get_one(gamereward_id, csv: Optional[bool] = None):
|
||||||
try:
|
try:
|
||||||
this_game_reward = GameRewards.get_by_id(gamereward_id)
|
this_game_reward = GameRewards.get_by_id(gamereward_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No game reward found with id {gamereward_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No game reward found with id {gamereward_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
data_list = [
|
data_list = [
|
||||||
['id', 'pack_type_id', 'player_id', 'money'],
|
["id", "pack_type_id", "player_id", "money"],
|
||||||
[this_game_reward.id, this_game_reward.pack_type_id if this_game_reward.pack_type else None,
|
[
|
||||||
this_game_reward.player_id if this_game_reward.player else None, this_game_reward.money]
|
this_game_reward.id,
|
||||||
|
this_game_reward.pack_type_id if this_game_reward.pack_type else None,
|
||||||
|
this_game_reward.player_id if this_game_reward.player else None,
|
||||||
|
this_game_reward.money,
|
||||||
|
],
|
||||||
]
|
]
|
||||||
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
||||||
|
|
||||||
return Response(content=return_val, media_type='text/csv')
|
return Response(content=return_val, media_type="text/csv")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return_val = model_to_dict(this_game_reward)
|
return_val = model_to_dict(this_game_reward)
|
||||||
return return_val
|
return return_val
|
||||||
|
|
||||||
|
|
||||||
@router.post('')
|
@router.post("")
|
||||||
async def v1_gamerewards_post(game_reward: GameRewardModel, token: str = Depends(oauth2_scheme)):
|
async def v1_gamerewards_post(
|
||||||
|
game_reward: GameRewardModel, token: str = Depends(oauth2_scheme)
|
||||||
|
):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('Bad Token: [REDACTED]')
|
logging.warning("Bad Token: [REDACTED]")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=401,
|
status_code=401,
|
||||||
detail='You are not authorized to post game rewards. This event has been logged.'
|
detail="You are not authorized to post game rewards. This event has been logged.",
|
||||||
)
|
)
|
||||||
|
|
||||||
this_award = GameRewards(
|
this_award = GameRewards(
|
||||||
name=game_reward.name,
|
name=game_reward.name,
|
||||||
pack_type_id=game_reward.pack_type_id,
|
pack_type_id=game_reward.pack_type_id,
|
||||||
player_id=game_reward.player_id,
|
player_id=game_reward.player_id,
|
||||||
money=game_reward.money
|
money=game_reward.money,
|
||||||
)
|
)
|
||||||
|
|
||||||
saved = this_award.save()
|
saved = this_award.save()
|
||||||
@ -104,24 +121,31 @@ async def v1_gamerewards_post(game_reward: GameRewardModel, token: str = Depends
|
|||||||
else:
|
else:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=418,
|
status_code=418,
|
||||||
detail='Well slap my ass and call me a teapot; I could not save that roster'
|
detail="Well slap my ass and call me a teapot; I could not save that roster",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.patch('/{game_reward_id}')
|
@router.patch("/{game_reward_id}")
|
||||||
async def v1_gamerewards_patch(
|
async def v1_gamerewards_patch(
|
||||||
game_reward_id: int, name: Optional[str] = None, pack_type_id: Optional[int] = None,
|
game_reward_id: int,
|
||||||
player_id: Optional[int] = None, money: Optional[int] = None, token: str = Depends(oauth2_scheme)):
|
name: Optional[str] = None,
|
||||||
|
pack_type_id: Optional[int] = None,
|
||||||
|
player_id: Optional[int] = None,
|
||||||
|
money: Optional[int] = None,
|
||||||
|
token: str = Depends(oauth2_scheme),
|
||||||
|
):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('Bad Token: [REDACTED]')
|
logging.warning("Bad Token: [REDACTED]")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=401,
|
status_code=401,
|
||||||
detail='You are not authorized to patch gamerewards. This event has been logged.'
|
detail="You are not authorized to patch gamerewards. This event has been logged.",
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
this_game_reward = GameRewards.get_by_id(game_reward_id)
|
this_game_reward = GameRewards.get_by_id(game_reward_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No game reward found with id {game_reward_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No game reward found with id {game_reward_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if name is not None:
|
if name is not None:
|
||||||
this_game_reward.name = name
|
this_game_reward.name = name
|
||||||
@ -147,27 +171,32 @@ async def v1_gamerewards_patch(
|
|||||||
else:
|
else:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=418,
|
status_code=418,
|
||||||
detail='Well slap my ass and call me a teapot; I could not save that rarity'
|
detail="Well slap my ass and call me a teapot; I could not save that rarity",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.delete('/{gamereward_id}')
|
@router.delete("/{gamereward_id}")
|
||||||
async def v1_gamerewards_delete(gamereward_id, token: str = Depends(oauth2_scheme)):
|
async def v1_gamerewards_delete(gamereward_id, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('Bad Token: [REDACTED]')
|
logging.warning("Bad Token: [REDACTED]")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=401,
|
status_code=401,
|
||||||
detail='You are not authorized to delete awards. This event has been logged.'
|
detail="You are not authorized to delete awards. This event has been logged.",
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
this_award = GameRewards.get_by_id(gamereward_id)
|
this_award = GameRewards.get_by_id(gamereward_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No award found with id {gamereward_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No award found with id {gamereward_id}"
|
||||||
|
)
|
||||||
|
|
||||||
count = this_award.delete_instance()
|
count = this_award.delete_instance()
|
||||||
|
|
||||||
if count == 1:
|
if count == 1:
|
||||||
raise HTTPException(status_code=200, detail=f'Game Reward {gamereward_id} has been deleted')
|
raise HTTPException(
|
||||||
|
status_code=200, detail=f"Game Reward {gamereward_id} has been deleted"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail=f'Game Reward {gamereward_id} was not deleted')
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Game Reward {gamereward_id} was not deleted"
|
||||||
|
)
|
||||||
|
|||||||
@ -73,6 +73,7 @@ async def get_players(
|
|||||||
key_mlbam: list = Query(default=None),
|
key_mlbam: list = Query(default=None),
|
||||||
offense_col: list = Query(default=None),
|
offense_col: list = Query(default=None),
|
||||||
csv: Optional[bool] = False,
|
csv: Optional[bool] = False,
|
||||||
|
limit: int = 100,
|
||||||
):
|
):
|
||||||
all_players = MlbPlayer.select().order_by(MlbPlayer.id)
|
all_players = MlbPlayer.select().order_by(MlbPlayer.id)
|
||||||
|
|
||||||
@ -101,6 +102,8 @@ async def get_players(
|
|||||||
if offense_col is not None:
|
if offense_col is not None:
|
||||||
all_players = all_players.where(MlbPlayer.offense_col << offense_col)
|
all_players = all_players.where(MlbPlayer.offense_col << offense_col)
|
||||||
|
|
||||||
|
all_players = all_players.limit(max(0, min(limit, 500)))
|
||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
return_val = query_to_csv(all_players)
|
return_val = query_to_csv(all_players)
|
||||||
return Response(content=return_val, media_type="text/csv")
|
return Response(content=return_val, media_type="text/csv")
|
||||||
@ -222,7 +225,7 @@ async def post_one_player(player: PlayerModel, token: str = Depends(oauth2_schem
|
|||||||
| (MlbPlayer.key_bbref == player.key_bbref)
|
| (MlbPlayer.key_bbref == player.key_bbref)
|
||||||
)
|
)
|
||||||
if dupes.count() > 0:
|
if dupes.count() > 0:
|
||||||
logging.info(f"POST /mlbplayers/one - dupes found:")
|
logging.info("POST /mlbplayers/one - dupes found:")
|
||||||
for x in dupes:
|
for x in dupes:
|
||||||
logging.info(f"{x}")
|
logging.info(f"{x}")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
|
|||||||
@ -8,10 +8,7 @@ from ..db_engine import Result, model_to_dict, Team, DataError, DoesNotExist
|
|||||||
from ..dependencies import oauth2_scheme, valid_token
|
from ..dependencies import oauth2_scheme, valid_token
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter(
|
router = APIRouter(prefix="/api/v2/results", tags=["results"])
|
||||||
prefix='/api/v2/results',
|
|
||||||
tags=['results']
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ResultModel(pydantic.BaseModel):
|
class ResultModel(pydantic.BaseModel):
|
||||||
@ -31,15 +28,29 @@ class ResultModel(pydantic.BaseModel):
|
|||||||
game_type: str
|
game_type: str
|
||||||
|
|
||||||
|
|
||||||
@router.get('')
|
@router.get("")
|
||||||
async def get_results(
|
async def get_results(
|
||||||
away_team_id: Optional[int] = None, home_team_id: Optional[int] = None, team_one_id: Optional[int] = None,
|
away_team_id: Optional[int] = None,
|
||||||
team_two_id: Optional[int] = None, away_score_min: Optional[int] = None, away_score_max: Optional[int] = None,
|
home_team_id: Optional[int] = None,
|
||||||
home_score_min: Optional[int] = None, home_score_max: Optional[int] = None, bothscore_min: Optional[int] = None,
|
team_one_id: Optional[int] = None,
|
||||||
bothscore_max: Optional[int] = None, season: Optional[int] = None, week: Optional[int] = None,
|
team_two_id: Optional[int] = None,
|
||||||
week_start: Optional[int] = None, week_end: Optional[int] = None, ranked: Optional[bool] = None,
|
away_score_min: Optional[int] = None,
|
||||||
short_game: Optional[bool] = None, game_type: Optional[str] = None, vs_ai: Optional[bool] = None,
|
away_score_max: Optional[int] = None,
|
||||||
csv: Optional[bool] = None):
|
home_score_min: Optional[int] = None,
|
||||||
|
home_score_max: Optional[int] = None,
|
||||||
|
bothscore_min: Optional[int] = None,
|
||||||
|
bothscore_max: Optional[int] = None,
|
||||||
|
season: Optional[int] = None,
|
||||||
|
week: Optional[int] = None,
|
||||||
|
week_start: Optional[int] = None,
|
||||||
|
week_end: Optional[int] = None,
|
||||||
|
ranked: Optional[bool] = None,
|
||||||
|
short_game: Optional[bool] = None,
|
||||||
|
game_type: Optional[str] = None,
|
||||||
|
vs_ai: Optional[bool] = None,
|
||||||
|
csv: Optional[bool] = None,
|
||||||
|
limit: int = 100,
|
||||||
|
):
|
||||||
all_results = Result.select()
|
all_results = Result.select()
|
||||||
|
|
||||||
# if all_results.count() == 0:
|
# if all_results.count() == 0:
|
||||||
@ -51,28 +62,40 @@ async def get_results(
|
|||||||
this_team = Team.get_by_id(away_team_id)
|
this_team = Team.get_by_id(away_team_id)
|
||||||
all_results = all_results.where(Result.away_team == this_team)
|
all_results = all_results.where(Result.away_team == this_team)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No team found with id {away_team_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No team found with id {away_team_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if home_team_id is not None:
|
if home_team_id is not None:
|
||||||
try:
|
try:
|
||||||
this_team = Team.get_by_id(home_team_id)
|
this_team = Team.get_by_id(home_team_id)
|
||||||
all_results = all_results.where(Result.home_team == this_team)
|
all_results = all_results.where(Result.home_team == this_team)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No team found with id {home_team_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No team found with id {home_team_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if team_one_id is not None:
|
if team_one_id is not None:
|
||||||
try:
|
try:
|
||||||
this_team = Team.get_by_id(team_one_id)
|
this_team = Team.get_by_id(team_one_id)
|
||||||
all_results = all_results.where((Result.home_team == this_team) | (Result.away_team == this_team))
|
all_results = all_results.where(
|
||||||
|
(Result.home_team == this_team) | (Result.away_team == this_team)
|
||||||
|
)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No team found with id {team_one_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No team found with id {team_one_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if team_two_id is not None:
|
if team_two_id is not None:
|
||||||
try:
|
try:
|
||||||
this_team = Team.get_by_id(team_two_id)
|
this_team = Team.get_by_id(team_two_id)
|
||||||
all_results = all_results.where((Result.home_team == this_team) | (Result.away_team == this_team))
|
all_results = all_results.where(
|
||||||
|
(Result.home_team == this_team) | (Result.away_team == this_team)
|
||||||
|
)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No team found with id {team_two_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No team found with id {team_two_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if away_score_min is not None:
|
if away_score_min is not None:
|
||||||
all_results = all_results.where(Result.away_score >= away_score_min)
|
all_results = all_results.where(Result.away_score >= away_score_min)
|
||||||
@ -87,10 +110,14 @@ async def get_results(
|
|||||||
all_results = all_results.where(Result.home_score <= home_score_max)
|
all_results = all_results.where(Result.home_score <= home_score_max)
|
||||||
|
|
||||||
if bothscore_min is not None:
|
if bothscore_min is not None:
|
||||||
all_results = all_results.where((Result.home_score >= bothscore_min) & (Result.away_score >= bothscore_min))
|
all_results = all_results.where(
|
||||||
|
(Result.home_score >= bothscore_min) & (Result.away_score >= bothscore_min)
|
||||||
|
)
|
||||||
|
|
||||||
if bothscore_max is not None:
|
if bothscore_max is not None:
|
||||||
all_results = all_results.where((Result.home_score <= bothscore_max) & (Result.away_score <= bothscore_max))
|
all_results = all_results.where(
|
||||||
|
(Result.home_score <= bothscore_max) & (Result.away_score <= bothscore_max)
|
||||||
|
)
|
||||||
|
|
||||||
if season is not None:
|
if season is not None:
|
||||||
all_results = all_results.where(Result.season == season)
|
all_results = all_results.where(Result.season == season)
|
||||||
@ -114,6 +141,8 @@ async def get_results(
|
|||||||
all_results = all_results.where(Result.game_type == game_type)
|
all_results = all_results.where(Result.game_type == game_type)
|
||||||
|
|
||||||
all_results = all_results.order_by(Result.id)
|
all_results = all_results.order_by(Result.id)
|
||||||
|
limit = max(0, min(limit, 500))
|
||||||
|
all_results = all_results.limit(limit)
|
||||||
# Not functional
|
# Not functional
|
||||||
# if vs_ai is not None:
|
# if vs_ai is not None:
|
||||||
# AwayTeam = Team.alias()
|
# AwayTeam = Team.alias()
|
||||||
@ -134,60 +163,115 @@ async def get_results(
|
|||||||
# logging.info(f'Result Query:\n\n{all_results}')
|
# logging.info(f'Result Query:\n\n{all_results}')
|
||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
data_list = [['id', 'away_abbrev', 'home_abbrev', 'away_score', 'home_score', 'away_tv', 'home_tv',
|
data_list = [
|
||||||
'game_type', 'season', 'week', 'short_game', 'ranked']]
|
[
|
||||||
|
"id",
|
||||||
|
"away_abbrev",
|
||||||
|
"home_abbrev",
|
||||||
|
"away_score",
|
||||||
|
"home_score",
|
||||||
|
"away_tv",
|
||||||
|
"home_tv",
|
||||||
|
"game_type",
|
||||||
|
"season",
|
||||||
|
"week",
|
||||||
|
"short_game",
|
||||||
|
"ranked",
|
||||||
|
]
|
||||||
|
]
|
||||||
for line in all_results:
|
for line in all_results:
|
||||||
data_list.append([
|
data_list.append(
|
||||||
line.id, line.away_team.abbrev, line.home_team.abbrev, line.away_score, line.home_score,
|
[
|
||||||
line.away_team_value, line.home_team_value, line.game_type if line.game_type else 'minor-league',
|
line.id,
|
||||||
line.season, line.week, line.short_game, line.ranked
|
line.away_team.abbrev,
|
||||||
])
|
line.home_team.abbrev,
|
||||||
|
line.away_score,
|
||||||
|
line.home_score,
|
||||||
|
line.away_team_value,
|
||||||
|
line.home_team_value,
|
||||||
|
line.game_type if line.game_type else "minor-league",
|
||||||
|
line.season,
|
||||||
|
line.week,
|
||||||
|
line.short_game,
|
||||||
|
line.ranked,
|
||||||
|
]
|
||||||
|
)
|
||||||
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
||||||
|
|
||||||
return Response(content=return_val, media_type='text/csv')
|
return Response(content=return_val, media_type="text/csv")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return_val = {'count': all_results.count(), 'results': []}
|
return_val = {"count": all_results.count(), "results": []}
|
||||||
for x in all_results:
|
for x in all_results:
|
||||||
return_val['results'].append(model_to_dict(x))
|
return_val["results"].append(model_to_dict(x))
|
||||||
|
|
||||||
return return_val
|
return return_val
|
||||||
|
|
||||||
|
|
||||||
@router.get('/{result_id}')
|
@router.get("/{result_id}")
|
||||||
async def get_one_results(result_id, csv: Optional[bool] = None):
|
async def get_one_results(result_id, csv: Optional[bool] = None):
|
||||||
try:
|
try:
|
||||||
this_result = Result.get_by_id(result_id)
|
this_result = Result.get_by_id(result_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No result found with id {result_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No result found with id {result_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
data_list = [
|
data_list = [
|
||||||
['id', 'away_abbrev', 'home_abbrev', 'away_score', 'home_score', 'away_tv', 'home_tv', 'game_type',
|
[
|
||||||
'season', 'week', 'game_type'],
|
"id",
|
||||||
[this_result.id, this_result.away_team.abbrev, this_result.away_team.abbrev, this_result.away_score,
|
"away_abbrev",
|
||||||
this_result.home_score, this_result.away_team_value, this_result.home_team_value,
|
"home_abbrev",
|
||||||
this_result.game_type if this_result.game_type else 'minor-league',
|
"away_score",
|
||||||
this_result.season, this_result.week, this_result.game_type]
|
"home_score",
|
||||||
|
"away_tv",
|
||||||
|
"home_tv",
|
||||||
|
"game_type",
|
||||||
|
"season",
|
||||||
|
"week",
|
||||||
|
"game_type",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
this_result.id,
|
||||||
|
this_result.away_team.abbrev,
|
||||||
|
this_result.away_team.abbrev,
|
||||||
|
this_result.away_score,
|
||||||
|
this_result.home_score,
|
||||||
|
this_result.away_team_value,
|
||||||
|
this_result.home_team_value,
|
||||||
|
this_result.game_type if this_result.game_type else "minor-league",
|
||||||
|
this_result.season,
|
||||||
|
this_result.week,
|
||||||
|
this_result.game_type,
|
||||||
|
],
|
||||||
]
|
]
|
||||||
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
||||||
|
|
||||||
return Response(content=return_val, media_type='text/csv')
|
return Response(content=return_val, media_type="text/csv")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return_val = model_to_dict(this_result)
|
return_val = model_to_dict(this_result)
|
||||||
return return_val
|
return return_val
|
||||||
|
|
||||||
|
|
||||||
@router.get('/team/{team_id}')
|
@router.get("/team/{team_id}")
|
||||||
async def get_team_results(
|
async def get_team_results(
|
||||||
team_id: int, season: Optional[int] = None, week: Optional[int] = None, csv: Optional[bool] = False):
|
team_id: int,
|
||||||
all_results = Result.select().where((Result.away_team_id == team_id) | (Result.home_team_id == team_id)).order_by(Result.id)
|
season: Optional[int] = None,
|
||||||
|
week: Optional[int] = None,
|
||||||
|
csv: Optional[bool] = False,
|
||||||
|
):
|
||||||
|
all_results = (
|
||||||
|
Result.select()
|
||||||
|
.where((Result.away_team_id == team_id) | (Result.home_team_id == team_id))
|
||||||
|
.order_by(Result.id)
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
this_team = Team.get_by_id(team_id)
|
this_team = Team.get_by_id(team_id)
|
||||||
except DoesNotExist as e:
|
except DoesNotExist:
|
||||||
logging.error(f'Unknown team id {team_id} trying to pull team results')
|
logging.error(f"Unknown team id {team_id} trying to pull team results")
|
||||||
raise HTTPException(404, f'Team id {team_id} not found')
|
raise HTTPException(404, f"Team id {team_id} not found")
|
||||||
|
|
||||||
if season is not None:
|
if season is not None:
|
||||||
all_results = all_results.where(Result.season == season)
|
all_results = all_results.where(Result.season == season)
|
||||||
@ -224,31 +308,38 @@ async def get_team_results(
|
|||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
data_list = [
|
data_list = [
|
||||||
['team_id', 'ranked_wins', 'ranked_losses', 'casual_wins', 'casual_losses', 'team_ranking'],
|
[
|
||||||
[team_id, r_wins, r_loss, c_wins, c_loss, this_team.ranking]
|
"team_id",
|
||||||
|
"ranked_wins",
|
||||||
|
"ranked_losses",
|
||||||
|
"casual_wins",
|
||||||
|
"casual_losses",
|
||||||
|
"team_ranking",
|
||||||
|
],
|
||||||
|
[team_id, r_wins, r_loss, c_wins, c_loss, this_team.ranking],
|
||||||
]
|
]
|
||||||
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
return_val = DataFrame(data_list).to_csv(header=False, index=False)
|
||||||
|
|
||||||
return Response(content=return_val, media_type='text/csv')
|
return Response(content=return_val, media_type="text/csv")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return_val = {
|
return_val = {
|
||||||
'team': model_to_dict(this_team),
|
"team": model_to_dict(this_team),
|
||||||
'ranked_wins': r_wins,
|
"ranked_wins": r_wins,
|
||||||
'ranked_losses': r_loss,
|
"ranked_losses": r_loss,
|
||||||
'casual_wins': c_wins,
|
"casual_wins": c_wins,
|
||||||
'casual_losses': c_loss,
|
"casual_losses": c_loss,
|
||||||
}
|
}
|
||||||
return return_val
|
return return_val
|
||||||
|
|
||||||
|
|
||||||
@router.post('')
|
@router.post("")
|
||||||
async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)):
|
async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('Bad Token: [REDACTED]')
|
logging.warning("Bad Token: [REDACTED]")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=401,
|
status_code=401,
|
||||||
detail='You are not authorized to post results. This event has been logged.'
|
detail="You are not authorized to post results. This event has been logged.",
|
||||||
)
|
)
|
||||||
|
|
||||||
this_result = Result(**result.__dict__)
|
this_result = Result(**result.__dict__)
|
||||||
@ -256,24 +347,28 @@ async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)):
|
|||||||
|
|
||||||
if result.ranked:
|
if result.ranked:
|
||||||
if not result.away_team_ranking:
|
if not result.away_team_ranking:
|
||||||
error = f'Ranked game did not include away team ({result.away_team_id}) ranking.'
|
error = f"Ranked game did not include away team ({result.away_team_id}) ranking."
|
||||||
logging.error(error)
|
logging.error(error)
|
||||||
raise DataError(error)
|
raise DataError(error)
|
||||||
if not result.home_team_ranking:
|
if not result.home_team_ranking:
|
||||||
error = f'Ranked game did not include home team ({result.home_team_id}) ranking.'
|
error = f"Ranked game did not include home team ({result.home_team_id}) ranking."
|
||||||
logging.error(error)
|
logging.error(error)
|
||||||
raise DataError(error)
|
raise DataError(error)
|
||||||
|
|
||||||
k_value = 20 if result.short_game else 60
|
k_value = 20 if result.short_game else 60
|
||||||
ratio = (result.home_team_ranking - result.away_team_ranking) / 400
|
ratio = (result.home_team_ranking - result.away_team_ranking) / 400
|
||||||
exp_score = 1 / (1 + (10 ** ratio))
|
exp_score = 1 / (1 + (10**ratio))
|
||||||
away_win = True if result.away_score > result.home_score else False
|
away_win = True if result.away_score > result.home_score else False
|
||||||
total_delta = k_value * exp_score
|
total_delta = k_value * exp_score
|
||||||
high_delta = total_delta * exp_score if exp_score > .5 else total_delta * (1 - exp_score)
|
high_delta = (
|
||||||
|
total_delta * exp_score
|
||||||
|
if exp_score > 0.5
|
||||||
|
else total_delta * (1 - exp_score)
|
||||||
|
)
|
||||||
low_delta = total_delta - high_delta
|
low_delta = total_delta - high_delta
|
||||||
|
|
||||||
# exp_score > .5 means away team is favorite
|
# exp_score > .5 means away team is favorite
|
||||||
if exp_score > .5 and away_win:
|
if exp_score > 0.5 and away_win:
|
||||||
final_delta = low_delta
|
final_delta = low_delta
|
||||||
away_delta = low_delta * 3
|
away_delta = low_delta * 3
|
||||||
home_delta = -low_delta
|
home_delta = -low_delta
|
||||||
@ -281,7 +376,7 @@ async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)):
|
|||||||
final_delta = high_delta
|
final_delta = high_delta
|
||||||
away_delta = high_delta * 3
|
away_delta = high_delta * 3
|
||||||
home_delta = -high_delta
|
home_delta = -high_delta
|
||||||
elif exp_score <= .5 and not away_win:
|
elif exp_score <= 0.5 and not away_win:
|
||||||
final_delta = low_delta
|
final_delta = low_delta
|
||||||
away_delta = -low_delta
|
away_delta = -low_delta
|
||||||
home_delta = low_delta * 3
|
home_delta = low_delta * 3
|
||||||
@ -294,18 +389,20 @@ async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)):
|
|||||||
away_delta = 0
|
away_delta = 0
|
||||||
home_delta = 0
|
home_delta = 0
|
||||||
|
|
||||||
logging.debug(f'/results ranking deltas\n\nk_value: {k_value} / ratio: {ratio} / '
|
logging.debug(
|
||||||
f'exp_score: {exp_score} / away_win: {away_win} / total_delta: {total_delta} / '
|
f"/results ranking deltas\n\nk_value: {k_value} / ratio: {ratio} / "
|
||||||
f'high_delta: {high_delta} / low_delta: {low_delta} / final_delta: {final_delta} / ')
|
f"exp_score: {exp_score} / away_win: {away_win} / total_delta: {total_delta} / "
|
||||||
|
f"high_delta: {high_delta} / low_delta: {low_delta} / final_delta: {final_delta} / "
|
||||||
|
)
|
||||||
|
|
||||||
away_team = Team.get_by_id(result.away_team_id)
|
away_team = Team.get_by_id(result.away_team_id)
|
||||||
away_team.ranking += away_delta
|
away_team.ranking += away_delta
|
||||||
away_team.save()
|
away_team.save()
|
||||||
logging.info(f'Just updated {away_team.abbrev} ranking to {away_team.ranking}')
|
logging.info(f"Just updated {away_team.abbrev} ranking to {away_team.ranking}")
|
||||||
home_team = Team.get_by_id(result.home_team_id)
|
home_team = Team.get_by_id(result.home_team_id)
|
||||||
home_team.ranking += home_delta
|
home_team.ranking += home_delta
|
||||||
home_team.save()
|
home_team.save()
|
||||||
logging.info(f'Just updated {home_team.abbrev} ranking to {home_team.ranking}')
|
logging.info(f"Just updated {home_team.abbrev} ranking to {home_team.ranking}")
|
||||||
|
|
||||||
if saved == 1:
|
if saved == 1:
|
||||||
return_val = model_to_dict(this_result)
|
return_val = model_to_dict(this_result)
|
||||||
@ -313,27 +410,38 @@ async def post_result(result: ResultModel, token: str = Depends(oauth2_scheme)):
|
|||||||
else:
|
else:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=418,
|
status_code=418,
|
||||||
detail='Well slap my ass and call me a teapot; I could not save that roster'
|
detail="Well slap my ass and call me a teapot; I could not save that roster",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.patch('/{result_id}')
|
@router.patch("/{result_id}")
|
||||||
async def patch_result(
|
async def patch_result(
|
||||||
result_id, away_team_id: Optional[int] = None, home_team_id: Optional[int] = None,
|
result_id,
|
||||||
away_score: Optional[int] = None, home_score: Optional[int] = None, away_team_value: Optional[int] = None,
|
away_team_id: Optional[int] = None,
|
||||||
home_team_value: Optional[int] = None, scorecard: Optional[str] = None, week: Optional[int] = None,
|
home_team_id: Optional[int] = None,
|
||||||
season: Optional[int] = None, short_game: Optional[bool] = None, game_type: Optional[str] = None,
|
away_score: Optional[int] = None,
|
||||||
token: str = Depends(oauth2_scheme)):
|
home_score: Optional[int] = None,
|
||||||
|
away_team_value: Optional[int] = None,
|
||||||
|
home_team_value: Optional[int] = None,
|
||||||
|
scorecard: Optional[str] = None,
|
||||||
|
week: Optional[int] = None,
|
||||||
|
season: Optional[int] = None,
|
||||||
|
short_game: Optional[bool] = None,
|
||||||
|
game_type: Optional[str] = None,
|
||||||
|
token: str = Depends(oauth2_scheme),
|
||||||
|
):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('Bad Token: [REDACTED]')
|
logging.warning("Bad Token: [REDACTED]")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=401,
|
status_code=401,
|
||||||
detail='You are not authorized to patch results. This event has been logged.'
|
detail="You are not authorized to patch results. This event has been logged.",
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
this_result = Result.get_by_id(result_id)
|
this_result = Result.get_by_id(result_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No result found with id {result_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No result found with id {result_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if away_team_id is not None:
|
if away_team_id is not None:
|
||||||
this_result.away_team_id = away_team_id
|
this_result.away_team_id = away_team_id
|
||||||
@ -377,27 +485,32 @@ async def patch_result(
|
|||||||
else:
|
else:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=418,
|
status_code=418,
|
||||||
detail='Well slap my ass and call me a teapot; I could not save that event'
|
detail="Well slap my ass and call me a teapot; I could not save that event",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.delete('/{result_id}')
|
@router.delete("/{result_id}")
|
||||||
async def delete_result(result_id, token: str = Depends(oauth2_scheme)):
|
async def delete_result(result_id, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('Bad Token: [REDACTED]')
|
logging.warning("Bad Token: [REDACTED]")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=401,
|
status_code=401,
|
||||||
detail='You are not authorized to post results. This event has been logged.'
|
detail="You are not authorized to post results. This event has been logged.",
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
this_result = Result.get_by_id(result_id)
|
this_result = Result.get_by_id(result_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No result found with id {result_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No result found with id {result_id}"
|
||||||
|
)
|
||||||
|
|
||||||
count = this_result.delete_instance()
|
count = this_result.delete_instance()
|
||||||
|
|
||||||
if count == 1:
|
if count == 1:
|
||||||
raise HTTPException(status_code=200, detail=f'Result {result_id} has been deleted')
|
raise HTTPException(
|
||||||
|
status_code=200, detail=f"Result {result_id} has been deleted"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail=f'Result {result_id} was not deleted')
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Result {result_id} was not deleted"
|
||||||
|
)
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@ -8,10 +8,7 @@ from ..db_engine import StratGame, model_to_dict, fn
|
|||||||
from ..dependencies import oauth2_scheme, valid_token
|
from ..dependencies import oauth2_scheme, valid_token
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter(
|
router = APIRouter(prefix="/api/v2/games", tags=["games"])
|
||||||
prefix='/api/v2/games',
|
|
||||||
tags=['games']
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class GameModel(pydantic.BaseModel):
|
class GameModel(pydantic.BaseModel):
|
||||||
@ -35,13 +32,22 @@ class GameList(pydantic.BaseModel):
|
|||||||
games: List[GameModel]
|
games: List[GameModel]
|
||||||
|
|
||||||
|
|
||||||
@router.get('')
|
@router.get("")
|
||||||
async def get_games(
|
async def get_games(
|
||||||
season: list = Query(default=None), forfeit: Optional[bool] = None, away_team_id: list = Query(default=None),
|
season: list = Query(default=None),
|
||||||
home_team_id: list = Query(default=None), team1_id: list = Query(default=None),
|
forfeit: Optional[bool] = None,
|
||||||
team2_id: list = Query(default=None), game_type: list = Query(default=None), ranked: Optional[bool] = None,
|
away_team_id: list = Query(default=None),
|
||||||
short_game: Optional[bool] = None, csv: Optional[bool] = False, short_output: bool = False,
|
home_team_id: list = Query(default=None),
|
||||||
gauntlet_id: Optional[int] = None):
|
team1_id: list = Query(default=None),
|
||||||
|
team2_id: list = Query(default=None),
|
||||||
|
game_type: list = Query(default=None),
|
||||||
|
ranked: Optional[bool] = None,
|
||||||
|
short_game: Optional[bool] = None,
|
||||||
|
csv: Optional[bool] = False,
|
||||||
|
short_output: bool = False,
|
||||||
|
gauntlet_id: Optional[int] = None,
|
||||||
|
limit: int = 100,
|
||||||
|
):
|
||||||
all_games = StratGame.select().order_by(StratGame.id)
|
all_games = StratGame.select().order_by(StratGame.id)
|
||||||
|
|
||||||
if season is not None:
|
if season is not None:
|
||||||
@ -68,49 +74,70 @@ async def get_games(
|
|||||||
if short_game is not None:
|
if short_game is not None:
|
||||||
all_games = all_games.where(StratGame.short_game == short_game)
|
all_games = all_games.where(StratGame.short_game == short_game)
|
||||||
if gauntlet_id is not None:
|
if gauntlet_id is not None:
|
||||||
all_games = all_games.where(StratGame.game_type.contains(f'gauntlet-{gauntlet_id}'))
|
all_games = all_games.where(
|
||||||
|
StratGame.game_type.contains(f"gauntlet-{gauntlet_id}")
|
||||||
|
)
|
||||||
|
|
||||||
|
all_games = all_games.limit(max(0, min(limit, 500)))
|
||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
return_vals = [model_to_dict(x) for x in all_games]
|
return_vals = [model_to_dict(x) for x in all_games]
|
||||||
for x in return_vals:
|
for x in return_vals:
|
||||||
x['away_abbrev'] = x['away_team']['abbrev']
|
x["away_abbrev"] = x["away_team"]["abbrev"]
|
||||||
x['home_abbrev'] = x['home_team']['abbrev']
|
x["home_abbrev"] = x["home_team"]["abbrev"]
|
||||||
del x['away_team'], x['home_team']
|
del x["away_team"], x["home_team"]
|
||||||
|
|
||||||
output = pd.DataFrame(return_vals)[[
|
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'
|
"id",
|
||||||
]]
|
"away_abbrev",
|
||||||
|
"home_abbrev",
|
||||||
|
"away_score",
|
||||||
|
"home_score",
|
||||||
|
"away_team_value",
|
||||||
|
"home_team_value",
|
||||||
|
"game_type",
|
||||||
|
"season",
|
||||||
|
"week",
|
||||||
|
"short_game",
|
||||||
|
"ranked",
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
return Response(content=output.to_csv(index=False), media_type='text/csv')
|
return Response(content=output.to_csv(index=False), media_type="text/csv")
|
||||||
|
|
||||||
return_val = {'count': all_games.count(), 'games': [
|
return_val = {
|
||||||
model_to_dict(x, recurse=not short_output) for x in all_games
|
"count": all_games.count(),
|
||||||
]}
|
"games": [model_to_dict(x, recurse=not short_output) for x in all_games],
|
||||||
|
}
|
||||||
return return_val
|
return return_val
|
||||||
|
|
||||||
|
|
||||||
@router.get('/{game_id}')
|
@router.get("/{game_id}")
|
||||||
async def get_one_game(game_id: int):
|
async def get_one_game(game_id: int):
|
||||||
this_game = StratGame.get_or_none(StratGame.id == game_id)
|
this_game = StratGame.get_or_none(StratGame.id == game_id)
|
||||||
if not this_game:
|
if not this_game:
|
||||||
raise HTTPException(status_code=404, detail=f'StratGame ID {game_id} not found')
|
raise HTTPException(status_code=404, detail=f"StratGame ID {game_id} not found")
|
||||||
|
|
||||||
g_result = model_to_dict(this_game)
|
g_result = model_to_dict(this_game)
|
||||||
return g_result
|
return g_result
|
||||||
|
|
||||||
|
|
||||||
@router.patch('/{game_id}')
|
@router.patch("/{game_id}")
|
||||||
async def patch_game(
|
async def patch_game(
|
||||||
game_id: int, game_type: Optional[str] = None, away_score: Optional[int] = None,
|
game_id: int,
|
||||||
home_score: Optional[int] = None, token: str = Depends(oauth2_scheme)):
|
game_type: Optional[str] = None,
|
||||||
|
away_score: Optional[int] = None,
|
||||||
|
home_score: Optional[int] = None,
|
||||||
|
token: str = Depends(oauth2_scheme),
|
||||||
|
):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('patch_game - Bad Token: [REDACTED]')
|
logging.warning("patch_game - Bad Token: [REDACTED]")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
this_game = StratGame.get_or_none(StratGame.id == game_id)
|
this_game = StratGame.get_or_none(StratGame.id == game_id)
|
||||||
if not this_game:
|
if not this_game:
|
||||||
raise HTTPException(status_code=404, detail=f'StratGame ID {game_id} not found')
|
raise HTTPException(status_code=404, detail=f"StratGame ID {game_id} not found")
|
||||||
|
|
||||||
if away_score is not None:
|
if away_score is not None:
|
||||||
this_game.away_score = away_score
|
this_game.away_score = away_score
|
||||||
@ -123,14 +150,14 @@ async def patch_game(
|
|||||||
g_result = model_to_dict(this_game)
|
g_result = model_to_dict(this_game)
|
||||||
return g_result
|
return g_result
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail=f'Unable to patch game {game_id}')
|
raise HTTPException(status_code=500, detail=f"Unable to patch game {game_id}")
|
||||||
|
|
||||||
|
|
||||||
@router.post('')
|
@router.post("")
|
||||||
async def post_game(this_game: GameModel, token: str = Depends(oauth2_scheme)):
|
async def post_game(this_game: GameModel, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('post_games - Bad Token: [REDACTED]')
|
logging.warning("post_games - Bad Token: [REDACTED]")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
this_game = StratGame(**this_game.dict())
|
this_game = StratGame(**this_game.dict())
|
||||||
|
|
||||||
@ -141,25 +168,25 @@ async def post_game(this_game: GameModel, token: str = Depends(oauth2_scheme)):
|
|||||||
else:
|
else:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=418,
|
status_code=418,
|
||||||
detail='Well slap my ass and call me a teapot; I could not save that game'
|
detail="Well slap my ass and call me a teapot; I could not save that game",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.delete('/{game_id}')
|
@router.delete("/{game_id}")
|
||||||
async def delete_game(game_id: int, token: str = Depends(oauth2_scheme)):
|
async def delete_game(game_id: int, token: str = Depends(oauth2_scheme)):
|
||||||
if not valid_token(token):
|
if not valid_token(token):
|
||||||
logging.warning('delete_game - Bad Token: [REDACTED]')
|
logging.warning("delete_game - Bad Token: [REDACTED]")
|
||||||
raise HTTPException(status_code=401, detail='Unauthorized')
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
|
|
||||||
this_game = StratGame.get_or_none(StratGame.id == game_id)
|
this_game = StratGame.get_or_none(StratGame.id == game_id)
|
||||||
if not this_game:
|
if not this_game:
|
||||||
raise HTTPException(status_code=404, detail=f'StratGame ID {game_id} not found')
|
raise HTTPException(status_code=404, detail=f"StratGame ID {game_id} not found")
|
||||||
|
|
||||||
count = this_game.delete_instance()
|
count = this_game.delete_instance()
|
||||||
|
|
||||||
if count == 1:
|
if count == 1:
|
||||||
return f'StratGame {game_id} has been deleted'
|
return f"StratGame {game_id} has been deleted"
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail=f'StratGame {game_id} could not be deleted')
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"StratGame {game_id} could not be deleted"
|
||||||
|
)
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user