Files
chat/shared/cache.py
Andrew K. Choi 4e3768a6ee
Some checks failed
continuous-integration/drone/push Build is failing
pipeline issues fix
2025-09-25 11:59:54 +09:00

46 lines
1.4 KiB
Python

import redis.asyncio as redis
from shared.config import settings
# Redis connection
redis_client = redis.from_url(settings.REDIS_URL)
class CacheService:
@staticmethod
async def set(key: str, value: str, expire: int = 3600):
"""Set cache with expiration"""
await redis_client.set(key, value, ex=expire)
@staticmethod
async def get(key: str) -> str:
"""Get cache value"""
return await redis_client.get(key)
@staticmethod
async def delete(key: str):
"""Delete cache key"""
await redis_client.delete(key)
@staticmethod
async def exists(key: str) -> bool:
"""Check if key exists"""
return await redis_client.exists(key)
@staticmethod
async def set_location(
user_id: int, latitude: float, longitude: float, expire: int = 300
):
"""Cache user location with expiration (5 minutes default)"""
location_data = f"{latitude},{longitude}"
await redis_client.set(f"location:{user_id}", location_data, ex=expire)
@staticmethod
async def get_location(user_id: int) -> tuple[float, float] | None:
"""Get cached user location"""
location_data = await redis_client.get(f"location:{user_id}")
if location_data:
lat, lng = location_data.decode().split(",")
return float(lat), float(lng)
return None