Merge pull request 'feat: add limit/pagination to rewards endpoint (#139)' (#152) from issue/139-feat-add-limit-pagination-to-rewards-endpoint into main
This commit is contained in:
commit
11794d8c2a
@ -9,10 +9,7 @@ from ..db_engine import Reward, model_to_dict, fn, DoesNotExist
|
|||||||
from ..dependencies import oauth2_scheme, valid_token
|
from ..dependencies import oauth2_scheme, valid_token
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter(
|
router = APIRouter(prefix="/api/v2/rewards", tags=["rewards"])
|
||||||
prefix='/api/v2/rewards',
|
|
||||||
tags=['rewards']
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class RewardModel(pydantic.BaseModel):
|
class RewardModel(pydantic.BaseModel):
|
||||||
@ -20,18 +17,25 @@ class RewardModel(pydantic.BaseModel):
|
|||||||
season: int
|
season: int
|
||||||
week: int
|
week: int
|
||||||
team_id: int
|
team_id: int
|
||||||
created: Optional[int] = int(datetime.timestamp(datetime.now())*1000)
|
created: Optional[int] = int(datetime.timestamp(datetime.now()) * 1000)
|
||||||
|
|
||||||
|
|
||||||
@router.get('')
|
@router.get("")
|
||||||
async def get_rewards(
|
async def get_rewards(
|
||||||
name: Optional[str] = None, in_name: Optional[str] = None, team_id: Optional[int] = None,
|
name: Optional[str] = None,
|
||||||
season: Optional[int] = None, week: Optional[int] = None, created_after: Optional[int] = None,
|
in_name: Optional[str] = None,
|
||||||
flat: Optional[bool] = False, csv: Optional[bool] = None):
|
team_id: Optional[int] = None,
|
||||||
|
season: Optional[int] = None,
|
||||||
|
week: Optional[int] = None,
|
||||||
|
created_after: Optional[int] = None,
|
||||||
|
flat: Optional[bool] = False,
|
||||||
|
csv: Optional[bool] = None,
|
||||||
|
limit: Optional[int] = 100,
|
||||||
|
):
|
||||||
all_rewards = Reward.select().order_by(Reward.id)
|
all_rewards = Reward.select().order_by(Reward.id)
|
||||||
|
|
||||||
if all_rewards.count() == 0:
|
if all_rewards.count() == 0:
|
||||||
raise HTTPException(status_code=404, detail=f'There are no rewards to filter')
|
raise HTTPException(status_code=404, detail="There are no rewards to filter")
|
||||||
|
|
||||||
if name is not None:
|
if name is not None:
|
||||||
all_rewards = all_rewards.where(fn.Lower(Reward.name) == name.lower())
|
all_rewards = all_rewards.where(fn.Lower(Reward.name) == name.lower())
|
||||||
@ -49,62 +53,71 @@ async def get_rewards(
|
|||||||
all_rewards = all_rewards.where(Reward.week == week)
|
all_rewards = all_rewards.where(Reward.week == week)
|
||||||
|
|
||||||
if all_rewards.count() == 0:
|
if all_rewards.count() == 0:
|
||||||
raise HTTPException(status_code=404, detail=f'No rewards found')
|
raise HTTPException(status_code=404, detail="No rewards found")
|
||||||
|
|
||||||
|
limit = max(0, min(limit, 500))
|
||||||
|
all_rewards = all_rewards.limit(limit)
|
||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
data_list = [['id', 'name', 'team', 'daily', 'created']]
|
data_list = [["id", "name", "team", "daily", "created"]]
|
||||||
for line in all_rewards:
|
for line in all_rewards:
|
||||||
data_list.append(
|
data_list.append(
|
||||||
[
|
[line.id, line.name, line.team.id, line.daily, line.created]
|
||||||
line.id, line.name, line.team.id, line.daily, line.created
|
|
||||||
]
|
|
||||||
)
|
)
|
||||||
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(), 'rewards': []}
|
return_val = {"count": all_rewards.count(), "rewards": []}
|
||||||
for x in all_rewards:
|
for x in all_rewards:
|
||||||
return_val['rewards'].append(model_to_dict(x, recurse=not flat))
|
return_val["rewards"].append(model_to_dict(x, recurse=not flat))
|
||||||
|
|
||||||
return return_val
|
return return_val
|
||||||
|
|
||||||
|
|
||||||
@router.get('/{reward_id}')
|
@router.get("/{reward_id}")
|
||||||
async def get_one_reward(reward_id, csv: Optional[bool] = False):
|
async def get_one_reward(reward_id, csv: Optional[bool] = False):
|
||||||
try:
|
try:
|
||||||
this_reward = Reward.get_by_id(reward_id)
|
this_reward = Reward.get_by_id(reward_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No reward found with id {reward_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No reward found with id {reward_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if csv:
|
if csv:
|
||||||
data_list = [
|
data_list = [
|
||||||
['id', 'name', 'card_count', 'description'],
|
["id", "name", "card_count", "description"],
|
||||||
[this_reward.id, this_reward.name, this_reward.team.id, this_reward.daily, this_reward.created]
|
[
|
||||||
|
this_reward.id,
|
||||||
|
this_reward.name,
|
||||||
|
this_reward.team.id,
|
||||||
|
this_reward.daily,
|
||||||
|
this_reward.created,
|
||||||
|
],
|
||||||
]
|
]
|
||||||
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_reward)
|
return_val = model_to_dict(this_reward)
|
||||||
return return_val
|
return return_val
|
||||||
|
|
||||||
|
|
||||||
@router.post('')
|
@router.post("")
|
||||||
async def post_rewards(reward: RewardModel, token: str = Depends(oauth2_scheme)):
|
async def post_rewards(reward: RewardModel, 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 rewards. This event has been logged.'
|
detail="You are not authorized to post rewards. This event has been logged.",
|
||||||
)
|
)
|
||||||
|
|
||||||
reward_data = reward.dict()
|
reward_data = reward.dict()
|
||||||
# Convert milliseconds timestamp to datetime for PostgreSQL
|
# Convert milliseconds timestamp to datetime for PostgreSQL
|
||||||
if reward_data.get('created'):
|
if reward_data.get("created"):
|
||||||
reward_data['created'] = datetime.fromtimestamp(reward_data['created'] / 1000)
|
reward_data["created"] = datetime.fromtimestamp(reward_data["created"] / 1000)
|
||||||
this_reward = Reward(**reward_data)
|
this_reward = Reward(**reward_data)
|
||||||
|
|
||||||
saved = this_reward.save()
|
saved = this_reward.save()
|
||||||
@ -114,24 +127,30 @@ async def post_rewards(reward: RewardModel, 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 cardset'
|
detail="Well slap my ass and call me a teapot; I could not save that cardset",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.patch('/{reward_id}')
|
@router.patch("/{reward_id}")
|
||||||
async def patch_reward(
|
async def patch_reward(
|
||||||
reward_id, name: Optional[str] = None, team_id: Optional[int] = None, created: Optional[int] = None,
|
reward_id,
|
||||||
token: str = Depends(oauth2_scheme)):
|
name: Optional[str] = None,
|
||||||
|
team_id: Optional[int] = None,
|
||||||
|
created: 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 rewards. This event has been logged.'
|
detail="You are not authorized to patch rewards. This event has been logged.",
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
this_reward = Reward.get_by_id(reward_id)
|
this_reward = Reward.get_by_id(reward_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No reward found with id {reward_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No reward found with id {reward_id}"
|
||||||
|
)
|
||||||
|
|
||||||
if name is not None:
|
if name is not None:
|
||||||
this_reward.name = name
|
this_reward.name = name
|
||||||
@ -147,28 +166,32 @@ async def patch_reward(
|
|||||||
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('/{reward_id}')
|
@router.delete("/{reward_id}")
|
||||||
async def delete_reward(reward_id, token: str = Depends(oauth2_scheme)):
|
async def delete_reward(reward_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 rewards. This event has been logged.'
|
detail="You are not authorized to delete rewards. This event has been logged.",
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
this_reward = Reward.get_by_id(reward_id)
|
this_reward = Reward.get_by_id(reward_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
raise HTTPException(status_code=404, detail=f'No reward found with id {reward_id}')
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"No reward found with id {reward_id}"
|
||||||
|
)
|
||||||
|
|
||||||
count = this_reward.delete_instance()
|
count = this_reward.delete_instance()
|
||||||
|
|
||||||
if count == 1:
|
if count == 1:
|
||||||
raise HTTPException(status_code=200, detail=f'Reward {reward_id} has been deleted')
|
raise HTTPException(
|
||||||
|
status_code=200, detail=f"Reward {reward_id} has been deleted"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
raise HTTPException(status_code=500, detail=f'Reward {reward_id} was not deleted')
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Reward {reward_id} was not deleted"
|
||||||
|
)
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user