From e8680667389a38227d66ddfbf31828254c0b5b98 Mon Sep 17 00:00:00 2001 From: Itamar Shefi Date: Wed, 6 Mar 2024 10:19:53 +0200 Subject: [PATCH] Cache secret fetching from db --- logic/game_logic.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/logic/game_logic.py b/logic/game_logic.py index d96581a..d740cb8 100644 --- a/logic/game_logic.py +++ b/logic/game_logic.py @@ -2,6 +2,7 @@ import datetime import heapq +from functools import lru_cache from typing import TYPE_CHECKING from typing import no_type_check @@ -31,10 +32,18 @@ def __init__(self, session: Session, dt: datetime.date | None = None): self.session = session async def get_secret(self) -> str | None: + return self._get_cached_secret(session=self.session, date=self.date) + + @staticmethod + @lru_cache + def _get_cached_secret(session: Session, date: datetime.date) -> str | None: + # TODO: this function is accessing db but is NOT ASYNC, which might be + # problematic if we choose to do async stuff with sql in the future. + # the reason for that is `@lru_cache` does not support async. query = select(tables.SecretWord) - query = query.where(tables.SecretWord.game_date == self.date) + query = query.where(tables.SecretWord.game_date == date) - with hs_transaction(self.session) as session: + with hs_transaction(session) as session: secret_word = session.exec(query).one_or_none() if secret_word is not None: return secret_word.word