38 lines
1007 B
Python
38 lines
1007 B
Python
|
from redis import Redis
|
||
|
|
||
|
from poker.constants import Rank
|
||
|
from poker.models import Hand
|
||
|
from poker.settings import CacheSettings
|
||
|
|
||
|
|
||
|
def get_redis_connection(settings: CacheSettings | None = None) -> Redis:
|
||
|
"""Get Redis connection."""
|
||
|
if settings is None:
|
||
|
settings = CacheSettings()
|
||
|
return Redis.from_url(settings.url)
|
||
|
|
||
|
|
||
|
class Cache:
|
||
|
"""Poker hands cache.
|
||
|
|
||
|
TODO: Only cache sorted hands.
|
||
|
"""
|
||
|
|
||
|
def __init__(self, conn: Redis | None = None) -> None:
|
||
|
"""Initialize cache."""
|
||
|
if conn is None:
|
||
|
self._conn = get_redis_connection()
|
||
|
else:
|
||
|
self._conn = conn
|
||
|
|
||
|
def get_rank(self, hand: Hand) -> Rank | None:
|
||
|
"""Get ranked hand from cache."""
|
||
|
key = str(hand)
|
||
|
rank = self._conn.get(key)
|
||
|
if rank is None:
|
||
|
return None
|
||
|
return Rank(rank)
|
||
|
|
||
|
def cache_rank(self, hand: Hand, rank: Rank) -> None:
|
||
|
"""Cache ranked hand."""
|
||
|
self._conn.set(str(hand), str(rank))
|