Update get_<x> functions to return x or None

This commit is contained in:
Cal Corum 2024-10-13 20:39:58 -05:00
parent a16ed26541
commit b35b25615d
5 changed files with 62 additions and 21 deletions

View File

@ -12,7 +12,7 @@ from helpers import PD_PLAYERS_ROLE_NAME, team_role, user_has_role
from in_game import ai_manager
from in_game.game_helpers import PUBLIC_FIELDS_CATEGORY_NAME, legal_check
from in_game.data_cache import get_pd_team
from in_game.gameplay_models import Lineup, Session, engine, get_player, player_description, select, Game, get_team
from in_game.gameplay_models import Lineup, Session, engine, get_player_or_none, player_description, select, Game, get_team_or_none
from in_game.gameplay_queries import get_channel_game_or_none, get_active_games_by_team
@ -63,14 +63,14 @@ class Gameplay(commands.Cog):
# await interaction.edit_original_response(content=f'Now to find this away team **{away_team_abbrev.upper()}**')
try:
away_team = await get_team(session, team_abbrev=away_team_abbrev)
away_team = await get_team_or_none(session, team_abbrev=away_team_abbrev)
except LookupError as e:
await interaction.edit_original_response(
content=f'Hm. I\'m not sure who **{away_team_abbrev}** is - check on that and try again!'
)
return
try:
home_team = await get_team(session, team_abbrev=home_team_abbrev)
home_team = await get_team_or_none(session, team_abbrev=home_team_abbrev)
except LookupError as e:
await interaction.edit_original_response(
content=f'Hm. I\'m not sure who **{home_team_abbrev}** is - check on that and try again!'
@ -142,7 +142,7 @@ class Gameplay(commands.Cog):
id_key = 'id'
if 'player_id' in human_sp_card['player']:
id_key = 'player_id'
human_sp_player = await get_player(session, human_sp_card['player'][id_key])
human_sp_player = await get_player_or_none(session, human_sp_card['player'][id_key])
if human_sp_card['team']['id'] != human_team.id:
logging.error(f'Card_id {sp_card_id} does not belong to {human_team.abbrev} in Game {this_game.id}')

View File

@ -101,8 +101,8 @@ class Team(TeamBase, table=True):
lineups: list['Lineup'] = Relationship(back_populates='team', cascade_delete=True)
async def get_team(
session: Session, team_id: int | None = None, gm_id: int | None = None, team_abbrev: str | None = None, skip_cache: bool = False) -> Team:
async def get_team_or_none(
session: Session, team_id: int | None = None, gm_id: int | None = None, team_abbrev: str | None = None, skip_cache: bool = False) -> Team | None:
if team_id is None and gm_id is None and team_abbrev is None:
err = 'One of "team_id", "gm_id", or "team_abbrev" must be included in search'
logging.error(f'gameplay_models - get_team - {err}')
@ -156,9 +156,7 @@ async def get_team(
for team in [x for x in t_query['teams'] if 'gauntlet' not in x['abbrev'].lower()]:
return cache_team(team)
err = 'Team not found'
logging.error(f'gameplay_models - get_team - {err}')
raise LookupError(err)
return None
class PlayerBase(SQLModel):
@ -214,7 +212,7 @@ def player_description(player: Player = None, player_dict: dict = None) -> str:
return r_val
async def get_player(session: Session, player_id: int, skip_cache: bool = False) -> Player:
async def get_player_or_none(session: Session, player_id: int, skip_cache: bool = False) -> Player | None:
if not skip_cache:
this_player = session.get(Player, player_id)
@ -244,8 +242,7 @@ async def get_player(session: Session, player_id: int, skip_cache: bool = False)
p_query['name'] = p_query['p_name']
return cache_player(p_query)
err = 'Player not found'
logging.error(f'gameplay_models - get_player - {err}')
return None
@ -256,6 +253,7 @@ class CardBase(SQLModel):
variant: int | None = Field(default=0)
created: datetime.datetime | None = Field(default=datetime.datetime.now())
class Card(CardBase, table=True):
player: Player = Relationship(back_populates='cards')
team: Team = Relationship(back_populates='cards',)
@ -302,6 +300,39 @@ async def get_or_create_ai_card(session: Session, player: Player, team: Team) ->
raise LookupError(err)
async def get_card_or_none(session: Session, card_id: int, skip_cache: bool = False) -> Card | None:
if not skip_cache:
this_card = session.get(Card, card_id)
if this_card is not None:
logging.info(f'we found a cached card: {this_card} / created: {this_card.created}')
tdelta = datetime.datetime.now() - this_card.created
logging.debug(f'tdelta: {tdelta}')
if tdelta.total_seconds() < CACHE_LIMIT:
return this_card
else:
session.delete(this_card)
session.commit()
def cache_card(json_data: dict) -> Card:
valid_card = CardBase.model_validate(json_data, from_attributes=True)
db_card = Card.model_validate(valid_card)
session.add(db_card)
session.commit()
session.refresh(db_card)
return db_card
c_query = await db_get('cards', object_id=card_id)
if c_query is not None:
c_query['team_id'] = c_query['team']['id']
if 'player_id' in c_query['player']:
c_query['player_id'] = c_query['player']['player_id']
else:
c_query['player_id'] = c_query['player']['id']
return cache_card(c_query)
return None
class Lineup(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)

View File

@ -1,7 +1,7 @@
import datetime
from sqlmodel import Session
from in_game.gameplay_models import CACHE_LIMIT, Card, Player, Team, get_or_create_ai_card, select
from in_game.gameplay_models import CACHE_LIMIT, Card, select, get_card_or_none
from factory import session_fixture
@ -18,3 +18,13 @@ def test_create_card(session: Session):
assert card_2.player_id == 12
assert card_2.team_id == 400
async def test_get_card_or_none(session: Session):
card_1 = session.get(Card, 1)
new_card_1 = await get_card_or_none(session, card_id=card_1.id)
assert card_1.created == new_card_1.created
new_card_2 = await get_card_or_none(session, card_id=55555)
assert new_card_2 is not None

View File

@ -1,7 +1,7 @@
import datetime
from sqlmodel import Session
from in_game.gameplay_models import CACHE_LIMIT, Player, player_description, select, get_player
from in_game.gameplay_models import CACHE_LIMIT, Player, player_description, select, get_player_or_none
from factory import session_fixture
@ -29,9 +29,9 @@ async def test_cached_players(session: Session):
assert (datetime.datetime.now() - player_2.created).total_seconds() > CACHE_LIMIT
new_player_1 = await get_player(session, player_id=player_1.id)
new_player_2 = await get_player(session, player_id=69)
new_player_3 = await get_player(session, player_id=6969)
new_player_1 = await get_player_or_none(session, player_id=player_1.id)
new_player_2 = await get_player_or_none(session, player_id=69)
new_player_3 = await get_player_or_none(session, player_id=6969)
assert player_1.created == new_player_1.created
assert (datetime.datetime.now() - new_player_2.created).total_seconds() < CACHE_LIMIT

View File

@ -1,7 +1,7 @@
import datetime
from sqlmodel import Session, select
from in_game.gameplay_models import Team, get_team, CACHE_LIMIT
from in_game.gameplay_models import Team, get_team_or_none, CACHE_LIMIT
from factory import session_fixture, new_teams_fixture, pytest
def test_create_team(session: Session, new_teams: list[Team]):
@ -37,9 +37,9 @@ async def test_team_cache(session: Session, new_teams: list[Team]):
assert (datetime.datetime.now() - team_3.created).total_seconds() > CACHE_LIMIT
new_team_31 = await get_team(session, team_id=team_31.id)
new_team_3 = await get_team(session, team_id=team_3.id)
new_team_4 = await get_team(session, team_abbrev='NYY')
new_team_31 = await get_team_or_none(session, team_id=team_31.id)
new_team_3 = await get_team_or_none(session, team_id=team_3.id)
new_team_4 = await get_team_or_none(session, team_abbrev='NYY')
assert team_31.created == new_team_31.created
assert (datetime.datetime.now() - new_team_3.created).total_seconds() < CACHE_LIMIT