Added admin, gamerewards, gauntletrewards, gauntletruns, notifications, paperdex

This commit is contained in:
Cal Corum 2023-09-14 22:05:51 -05:00
parent 177ca2c585
commit 144ced6875
7 changed files with 960 additions and 1 deletions

View File

@ -5,7 +5,7 @@ import os
from fastapi import FastAPI from fastapi import FastAPI
from.routers_v2 import current, teams, rarity, cardsets, players, packtypes, packs, cards, events, results, rewards, \ from.routers_v2 import current, teams, rarity, cardsets, players, packtypes, packs, cards, events, results, rewards, \
batstats, pitstats batstats, pitstats, notifications, paperdex, gamerewards, gauntletrewards, gauntletruns
app = FastAPI( app = FastAPI(
responses={404: {'description': 'Not found'}} responses={404: {'description': 'Not found'}}
@ -24,3 +24,8 @@ app.include_router(results.router)
app.include_router(rewards.router) app.include_router(rewards.router)
app.include_router(batstats.router) app.include_router(batstats.router)
app.include_router(pitstats.router) app.include_router(pitstats.router)
app.include_router(notifications.router)
app.include_router(paperdex.router)
app.include_router(gamerewards.router)
app.include_router(gauntletrewards.router)
app.include_router(gauntletruns.router)

40
app/routers_v2/admin.py Normal file
View File

@ -0,0 +1,40 @@
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Response
from typing import Optional
import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Player, model_to_dict, 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/v2/admin',
tags=['admin']
)
@router.post('/stl-fix')
async def stl_cardinals_fix(token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to post. This event has been logged.'
)
p_query = Player.update(mlbclub='St Louis Cardinals', franchise='St Louis Cardinals').where(
Player.mlbclub == 'St. Louis Cardinals'
).execute()
db.close()
return {'detail': f'Removed the period from St Louis'}

View File

@ -0,0 +1,194 @@
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Response
from typing import Optional
import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, GameRewards, model_to_dict, 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/v2/gamerewards',
tags=['gamerewards']
)
class GameRewardModel(pydantic.BaseModel):
name: str
pack_type_id: Optional[int] = None
player_id: Optional[int] = None
money: Optional[int] = None
@router.get('')
async def v1_gamerewards_get(
name: Optional[str] = None, pack_type_id: Optional[int] = None, player_id: Optional[int] = None,
money: Optional[int] = None, csv: Optional[bool] = None):
all_rewards = GameRewards.select()
# if all_rewards.count() == 0:
# db.close()
# raise HTTPException(status_code=404, detail=f'There are no awards to filter')
if name is not None:
all_rewards = all_rewards.where(GameRewards.name == name)
if pack_type_id is not None:
all_rewards = all_rewards.where(GameRewards.pack_type_id == pack_type_id)
if player_id is not None:
all_rewards = all_rewards.where(GameRewards.player_id == player_id)
if money is not None:
all_rewards = all_rewards.where(GameRewards.money == money)
if csv:
data_list = [['id', 'pack_type_id', 'player_id', 'money']]
for line in all_rewards:
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
])
return_val = DataFrame(data_list).to_csv(header=False, index=False)
db.close()
return Response(content=return_val, media_type='text/csv')
else:
return_val = {'count': all_rewards.count(), 'gamerewards': []}
for x in all_rewards:
return_val['gamerewards'].append(model_to_dict(x))
db.close()
return return_val
@router.get('/{gameaward_id}')
async def v1_gamerewards_get_one(gamereward_id, csv: Optional[bool] = None):
try:
this_game_reward = GameRewards.get_by_id(gamereward_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No game reward found with id {gamereward_id}')
if csv:
data_list = [
['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]
]
return_val = DataFrame(data_list).to_csv(header=False, index=False)
db.close()
return Response(content=return_val, media_type='text/csv')
else:
return_val = model_to_dict(this_game_reward)
db.close()
return return_val
@router.post('')
async def v1_gamerewards_post(game_reward: GameRewardModel, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to post game rewards. This event has been logged.'
)
this_award = GameRewards(
name=game_reward.name,
pack_type_id=game_reward.pack_type_id,
player_id=game_reward.player_id,
money=game_reward.money
)
saved = this_award.save()
if saved == 1:
return_val = model_to_dict(this_award)
db.close()
return return_val
else:
db.close()
raise HTTPException(
status_code=418,
detail='Well slap my ass and call me a teapot; I could not save that roster'
)
@router.patch('/{game_reward_id}')
async def v1_gamerewards_patch(
game_reward_id: int, 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):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to patch gamerewards. This event has been logged.'
)
try:
this_game_reward = GameRewards.get_by_id(game_reward_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No game reward found with id {game_reward_id}')
if name is not None:
this_game_reward.name = name
if pack_type_id is not None:
if not pack_type_id:
this_game_reward.pack_type_id = None
else:
this_game_reward.pack_type_id = pack_type_id
if player_id is not None:
if not player_id:
this_game_reward.player_id = None
else:
this_game_reward.player_id = player_id
if money is not None:
if not money:
this_game_reward.money = None
else:
this_game_reward.money = money
if this_game_reward.save() == 1:
return_val = model_to_dict(this_game_reward)
db.close()
return return_val
else:
raise HTTPException(
status_code=418,
detail='Well slap my ass and call me a teapot; I could not save that rarity'
)
@router.delete('/{gamereward_id}')
async def v1_gamerewards_delete(gamereward_id, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to delete awards. This event has been logged.'
)
try:
this_award = GameRewards.get_by_id(gamereward_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No award found with id {gamereward_id}')
count = this_award.delete_instance()
db.close()
if count == 1:
raise HTTPException(status_code=200, detail=f'Game Reward {gamereward_id} has been deleted')
else:
raise HTTPException(status_code=500, detail=f'Game Reward {gamereward_id} was not deleted')

View File

@ -0,0 +1,139 @@
from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional, List
import logging
import pydantic
from ..db_engine import db, GauntletReward, model_to_dict, chunked, DatabaseError
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/v2/gauntletrewards',
tags=['gauntletrewards']
)
class GauntletRewardModel(pydantic.BaseModel):
name: str
gauntlet_id: Optional[int] = 0
reward_id: Optional[int] = 0
win_num: Optional[int] = 0
loss_max: Optional[int] = 1
class GauntletRewardList(pydantic.BaseModel):
rewards: List[GauntletRewardModel]
@router.get('/api/v1/gauntletrewards')
async def v1_gauntletreward_get(
name: Optional[str] = None, gauntlet_id: Optional[int] = None, reward_id: list = Query(default=None),
win_num: Optional[int] = None, loss_max: Optional[int] = None):
all_rewards = GauntletReward.select()
if name is not None:
all_rewards = all_rewards.where(GauntletReward.name == name)
if gauntlet_id is not None:
all_rewards = all_rewards.where(GauntletReward.gauntlet_id == gauntlet_id)
if reward_id is not None:
all_rewards = all_rewards.where(GauntletReward.reward_id << reward_id)
if win_num is not None:
all_rewards = all_rewards.where(GauntletReward.win_num == win_num)
if loss_max is not None:
all_rewards = all_rewards.where(GauntletReward.loss_max >= loss_max)
all_rewards = all_rewards.order_by(-GauntletReward.loss_max, GauntletReward.win_num)
return_val = {'count': all_rewards.count(), 'rewards': []}
for x in all_rewards:
return_val['rewards'].append(model_to_dict(x))
db.close()
return return_val
@router.get('/api/v1/gauntletrewards/{gauntletreward_id}')
async def v1_gauntletreward_get_one(gauntletreward_id):
try:
this_reward = GauntletReward.get_by_id(gauntletreward_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No gauntlet reward found with id {gauntletreward_id}')
return_val = model_to_dict(this_reward)
db.close()
return return_val
@router.patch('/api/v1/gauntletrewards/{gauntletreward_id}')
async def v1_gauntletreward_patch(
gauntletreward_id, name: Optional[str] = None, gauntlet_id: Optional[int] = None,
reward_id: Optional[int] = None, win_num: Optional[int] = None, loss_max: Optional[int] = None,
token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to patch gauntlet rewards. This event has been logged.'
)
this_reward = GauntletReward.get_or_none(GauntletReward.id == gauntletreward_id)
if this_reward is None:
db.close()
raise KeyError(f'Gauntlet Reward ID {gauntletreward_id} not found')
if gauntlet_id is not None:
this_reward.gauntlet_id = gauntlet_id
if reward_id is not None:
this_reward.reward_id = reward_id
if win_num is not None:
this_reward.win_num = win_num
if loss_max is not None:
this_reward.loss_max = loss_max
if name is not None:
this_reward.name = name
if this_reward.save():
r_curr = model_to_dict(this_reward)
db.close()
return r_curr
else:
db.close()
raise DatabaseError(f'Unable to patch gauntlet reward {gauntletreward_id}')
@router.post('/api/v1/gauntletrewards')
async def v1_gauntletreward_post(gauntletreward: GauntletRewardList, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to post gauntlets. This event has been logged.'
)
all_rewards = []
for x in gauntletreward.rewards:
all_rewards.append(x.dict())
with db.atomic():
for batch in chunked(all_rewards, 15):
GauntletReward.insert_many(batch).on_conflict_replace().execute()
db.close()
return f'Inserted {len(all_rewards)} gauntlet rewards'
@router.delete('/api/v1/gauntletrewards/{gauntletreward_id}')
async def v1_gauntletreward_delete(gauntletreward_id):
if GauntletReward.delete_by_id(gauntletreward_id) == 1:
return f'Deleted gauntlet reward ID {gauntletreward_id}'
raise DatabaseError(f'Unable to delete gauntlet run {gauntletreward_id}')

View File

@ -0,0 +1,170 @@
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional
import logging
import pydantic
from ..db_engine import db, GauntletRun, model_to_dict, DatabaseError
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/v2/gauntletruns',
tags=['notifs']
)
class GauntletRunModel(pydantic.BaseModel):
team_id: int
gauntlet_id: int
wins: Optional[int] = 0
losses: Optional[int] = 0
gsheet: Optional[str] = None
created: Optional[int] = int(datetime.timestamp(datetime.now())*1000)
ended: Optional[int] = 0
@router.get('')
async def get_gauntletruns(
team_id: list = Query(default=None), wins: Optional[int] = None, wins_min: Optional[int] = None,
wins_max: Optional[int] = None, losses: Optional[int] = None, losses_min: Optional[int] = None,
losses_max: Optional[int] = None, gsheet: Optional[str] = None, created_after: Optional[int] = None,
created_before: Optional[int] = None, ended_after: Optional[int] = None, ended_before: Optional[int] = None,
is_active: Optional[bool] = None, gauntlet_id: list = Query(default=None), season: list = Query(default=None)):
all_gauntlets = GauntletRun.select()
if team_id is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.team_id << team_id)
if wins is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.wins == wins)
if wins_min is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.wins >= wins_min)
if wins_max is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.wins <= wins_max)
if losses is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.losses == losses)
if losses_min is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.losses >= losses_min)
if losses_max is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.losses <= losses_max)
if gsheet is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.gsheet == gsheet)
if created_after is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.created >= created_after)
if created_before is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.created <= created_before)
if ended_after is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.ended >= ended_after)
if ended_before is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.ended <= ended_before)
if is_active is not None:
if is_active is True:
all_gauntlets = all_gauntlets.where(GauntletRun.ended == 0)
else:
all_gauntlets = all_gauntlets.where(GauntletRun.ended != 0)
if gauntlet_id is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.gauntlet_id << gauntlet_id)
if season is not None:
all_gauntlets = all_gauntlets.where(GauntletRun.team.season << season)
return_val = {'count': all_gauntlets.count(), 'runs': []}
for x in all_gauntlets:
return_val['runs'].append(model_to_dict(x))
db.close()
return return_val
@router.get('/{gauntletrun_id}')
async def get_one_gauntletrun(gauntletrun_id):
try:
this_gauntlet = GauntletRun.get_by_id(gauntletrun_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No gauntlet found with id {gauntletrun_id}')
return_val = model_to_dict(this_gauntlet)
db.close()
return return_val
@router.patch('/{gauntletrun_id}')
async def patch_gauntletrun(
gauntletrun_id, team_id: Optional[int] = None, wins: Optional[int] = None, losses: Optional[int] = None,
gsheet: Optional[str] = None, created: Optional[bool] = None, ended: Optional[bool] = None,
token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to patch gauntlet runs. This event has been logged.'
)
this_run = GauntletRun.get_or_none(GauntletRun.id == gauntletrun_id)
if this_run is None:
db.close()
raise KeyError(f'Gauntlet Run ID {gauntletrun_id} not found')
if team_id is not None:
this_run.team_id = team_id
if wins is not None:
this_run.wins = wins
if losses is not None:
this_run.losses = losses
if gsheet is not None:
this_run.gsheet = gsheet
if created is not None:
if created is True:
this_run.created = int(datetime.timestamp(datetime.now())*1000)
else:
this_run.created = None
if ended is not None:
if ended is True:
this_run.ended = int(datetime.timestamp(datetime.now())*1000)
else:
this_run.ended = 0
if this_run.save():
r_curr = model_to_dict(this_run)
db.close()
return r_curr
else:
db.close()
raise DatabaseError(f'Unable to patch gauntlet run {gauntletrun_id}')
@router.post('')
async def post_gauntletrun(gauntletrun: GauntletRunModel, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to post gauntlets. This event has been logged.'
)
this_run = GauntletRun(**gauntletrun.dict())
if this_run.save():
r_run = model_to_dict(this_run)
db.close()
return r_run
else:
db.close()
raise DatabaseError(f'Unable to post gauntlet run')
@router.delete('/{gauntletrun_id}')
async def delete_gauntletrun(gauntletrun_id):
if GauntletRun.delete_by_id(gauntletrun_id) == 1:
return f'Deleted gauntlet run ID {gauntletrun_id}'
raise DatabaseError(f'Unable to delete gauntlet run {gauntletrun_id}')

View File

@ -0,0 +1,203 @@
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Response
from typing import Optional
import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Notification, model_to_dict, 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/v2/notifs',
tags=['notifs']
)
class NotifModel(pydantic.BaseModel):
created: int
title: str
desc: Optional[str] = None
field_name: str
message: str
about: Optional[str] = 'blank'
ack: Optional[bool] = False
@router.get('')
async def get_notifs(
created_after: Optional[int] = None, title: Optional[str] = None, desc: Optional[str] = None,
field_name: Optional[str] = None, in_desc: Optional[str] = None, about: Optional[str] = None,
ack: Optional[bool] = None, csv: Optional[bool] = None):
all_notif = Notification.select()
if all_notif.count() == 0:
db.close()
raise HTTPException(status_code=404, detail=f'There are no notifications to filter')
if created_after is not None:
all_notif = all_notif.where(Notification.created < created_after)
if title is not None:
all_notif = all_notif.where(Notification.title == title)
if desc is not None:
all_notif = all_notif.where(Notification.desc == desc)
if field_name is not None:
all_notif = all_notif.where(Notification.field_name == field_name)
if in_desc is not None:
all_notif = all_notif.where(fn.Lower(Notification.desc).contains(in_desc.lower()))
if about is not None:
all_notif = all_notif.where(Notification.about == about)
if ack is not None:
all_notif = all_notif.where(Notification.ack == ack)
if csv:
data_list = [['id', 'created', 'title', 'desc', 'field_name', 'message', 'about', 'ack']]
for line in all_notif:
data_list.append([
line.id, line.created, line.title, line.desc, line.field_name, line.message, line.about, line.ack
])
return_val = DataFrame(data_list).to_csv(header=False, index=False)
db.close()
return Response(content=return_val, media_type='text/csv')
else:
return_val = {'count': all_notif.count(), 'notifs': []}
for x in all_notif:
return_val['notifs'].append(model_to_dict(x))
db.close()
return return_val
@router.get('/{notif_id}')
async def get_one_notif(notif_id, csv: Optional[bool] = None):
try:
this_notif = Notification.get_by_id(notif_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No notification found with id {notif_id}')
if csv:
data_list = [
['id', 'created', 'title', 'desc', 'field_name', 'message', 'about', 'ack'],
[this_notif.id, this_notif.created, this_notif.title, this_notif.desc, this_notif.field_name,
this_notif.message, this_notif.about, this_notif.ack]
]
return_val = DataFrame(data_list).to_csv(header=False, index=False)
db.close()
return Response(content=return_val, media_type='text/csv')
else:
return_val = model_to_dict(this_notif)
db.close()
return return_val
@router.post('')
async def post_notif(notif: NotifModel, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to post notifications. This event has been logged.'
)
logging.info(f'new notif: {notif}')
this_notif = Notification(
created=notif.created,
title=notif.title,
desc=notif.desc,
field_name=notif.field_name,
message=notif.message,
about=notif.about,
)
saved = this_notif.save()
if saved == 1:
return_val = model_to_dict(this_notif)
db.close()
return return_val
else:
db.close()
raise HTTPException(
status_code=418,
detail='Well slap my ass and call me a teapot; I could not save that notification'
)
@router.patch('/{notif_id}')
async def patch_notif(
notif_id, created: Optional[int] = None, title: Optional[str] = None, desc: Optional[str] = None,
field_name: Optional[str] = None, message: Optional[str] = None, about: Optional[str] = None,
ack: Optional[bool] = None, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to patch notifications. This event has been logged.'
)
try:
this_notif = Notification.get_by_id(notif_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No notification found with id {notif_id}')
if title is not None:
this_notif.title = title
if desc is not None:
this_notif.desc = desc
if field_name is not None:
this_notif.field_name = field_name
if message is not None:
this_notif.message = message
if about is not None:
this_notif.about = about
if ack is not None:
this_notif.ack = ack
if created is not None:
this_notif.created = created
if this_notif.save() == 1:
return_val = model_to_dict(this_notif)
db.close()
return return_val
else:
raise HTTPException(
status_code=418,
detail='Well slap my ass and call me a teapot; I could not save that rarity'
)
@router.delete('/{notif_id}')
async def delete_notif(notif_id, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to delete notifications. This event has been logged.'
)
try:
this_notif = Notification.get_by_id(notif_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No notification found with id {notif_id}')
count = this_notif.delete_instance()
db.close()
if count == 1:
raise HTTPException(status_code=200, detail=f'Notification {notif_id} has been deleted')
else:
raise HTTPException(status_code=500, detail=f'Notification {notif_id} was not deleted')

208
app/routers_v2/paperdex.py Normal file
View File

@ -0,0 +1,208 @@
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Response
from typing import Optional
import logging
import pydantic
from pandas import DataFrame
from ..db_engine import db, Paperdex, model_to_dict, fn, Player, Cardset, Team
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/v2/paperdex',
tags=['paperdex']
)
class PaperdexModel(pydantic.BaseModel):
team_id: int
player_id: int
created: Optional[int] = int(datetime.timestamp(datetime.now())*1000)
@router.get('')
async def get_paperdex(
team_id: Optional[int] = None, player_id: Optional[int] = None, created_after: Optional[int] = None,
cardset_id: Optional[int] = None, created_before: Optional[int] = None, flat: Optional[bool] = False,
csv: Optional[bool] = None):
all_dex = Paperdex.select().join(Player).join(Cardset)
if all_dex.count() == 0:
db.close()
raise HTTPException(status_code=404, detail=f'There are no paperdex to filter')
if team_id is not None:
all_dex = all_dex.where(Paperdex.team_id == team_id)
if player_id is not None:
all_dex = all_dex.where(Paperdex.player_id == player_id)
if cardset_id is not None:
all_sets = Cardset.select().where(Cardset.id == cardset_id)
all_dex = all_dex.where(Paperdex.player.cardset.id == cardset_id)
if created_after is not None:
all_dex = all_dex.where(Paperdex.created >= created_after)
if created_before is not None:
all_dex = all_dex.where(Paperdex.created <= created_before)
# if all_dex.count() == 0:
# db.close()
# raise HTTPException(status_code=404, detail=f'No paperdex found')
if csv:
data_list = [['id', 'team_id', 'player_id', 'created']]
for line in all_dex:
data_list.append(
[
line.id, line.team.id, line.player.player_id, line.created
]
)
return_val = DataFrame(data_list).to_csv(header=False, index=False)
db.close()
return Response(content=return_val, media_type='text/csv')
else:
return_val = {'count': all_dex.count(), 'paperdex': []}
for x in all_dex:
return_val['paperdex'].append(model_to_dict(x, recurse=not flat))
db.close()
return return_val
@router.get('/{paperdex_id}')
async def get_one_paperdex(paperdex_id, csv: Optional[bool] = False):
try:
this_dex = Paperdex.get_by_id(paperdex_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No paperdex found with id {paperdex_id}')
if csv:
data_list = [
['id', 'team_id', 'player_id', 'created'],
[this_dex.id, this_dex.team.id, this_dex.player.id, this_dex.created]
]
return_val = DataFrame(data_list).to_csv(header=False, index=False)
db.close()
return Response(content=return_val, media_type='text/csv')
else:
return_val = model_to_dict(this_dex)
db.close()
return return_val
@router.post('')
async def post_paperdex(paperdex: PaperdexModel, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to post paperdex. This event has been logged.'
)
dupe_dex = Paperdex.get_or_none(Paperdex.team_id == paperdex.team_id, Paperdex.player_id == paperdex.player_id)
if dupe_dex:
return_val = model_to_dict(dupe_dex)
db.close()
return return_val
this_dex = Paperdex(
team_id=paperdex.team_id,
player_id=paperdex.player_id,
created=paperdex.created
)
saved = this_dex.save()
if saved == 1:
return_val = model_to_dict(this_dex)
db.close()
return return_val
else:
raise HTTPException(
status_code=418,
detail='Well slap my ass and call me a teapot; I could not save that dex'
)
@router.patch('/{paperdex_id}')
async def patch_paperdex(
paperdex_id, team_id: Optional[int] = None, player_id: Optional[int] = None, created: Optional[int] = None,
token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to patch paperdex. This event has been logged.'
)
try:
this_dex = Paperdex.get_by_id(paperdex_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No paperdex found with id {paperdex_id}')
if team_id is not None:
this_dex.team_id = team_id
if player_id is not None:
this_dex.player_id = player_id
if created is not None:
this_dex.created = created
if this_dex.save() == 1:
return_val = model_to_dict(this_dex)
db.close()
return return_val
else:
raise HTTPException(
status_code=418,
detail='Well slap my ass and call me a teapot; I could not save that rarity'
)
@router.delete('/{paperdex_id}')
async def delete_paperdex(paperdex_id, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='You are not authorized to delete rewards. This event has been logged.'
)
try:
this_dex = Paperdex.get_by_id(paperdex_id)
except Exception:
db.close()
raise HTTPException(status_code=404, detail=f'No paperdex found with id {paperdex_id}')
count = this_dex.delete_instance()
db.close()
if count == 1:
raise HTTPException(status_code=200, detail=f'Paperdex {this_dex} has been deleted')
else:
raise HTTPException(status_code=500, detail=f'Paperdex {this_dex} was not deleted')
@router.post('/wipe-ai')
async def wipe_ai_paperdex(token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning(f'Bad Token: {token}')
db.close()
raise HTTPException(
status_code=401,
detail='Unauthorized'
)
g_teams = Team.select().where(Team.abbrev.contains('Gauntlet'))
count = Paperdex.delete().where(Paperdex.team << g_teams).execute()
return f'Deleted {count} records'