Spaces:
Running
Running
| """ | |
| Redis connection and cache instance. | |
| Provides Redis client for OTP storage and rate limiting. | |
| """ | |
| import redis.asyncio as redis | |
| from app.core.logging import get_logger | |
| from app.core.config import settings | |
| logger = get_logger(__name__) | |
| # Redis client instance | |
| redis_client: redis.Redis = None | |
| async def connect_to_redis(): | |
| """ | |
| Establish connection to Redis. | |
| Called during application startup. | |
| """ | |
| global redis_client | |
| try: | |
| logger.info("Connecting to Redis", extra={ | |
| "host": settings.REDIS_HOST, | |
| "port": settings.REDIS_PORT, | |
| "db": settings.REDIS_DB | |
| }) | |
| redis_client = redis.Redis( | |
| host=settings.REDIS_HOST, | |
| port=settings.REDIS_PORT, | |
| password=settings.REDIS_PASSWORD, | |
| db=settings.REDIS_DB, | |
| decode_responses=True | |
| ) | |
| # Test the connection | |
| await redis_client.ping() | |
| logger.info("Successfully connected to Redis") | |
| except Exception as e: | |
| logger.error("Failed to connect to Redis", exc_info=e) | |
| raise | |
| async def close_redis_connection(): | |
| """ | |
| Close Redis connection. | |
| Called during application shutdown. | |
| """ | |
| global redis_client | |
| if redis_client: | |
| logger.info("Closing Redis connection") | |
| await redis_client.close() | |
| logger.info("Redis connection closed") | |
| def get_redis() -> redis.Redis: | |
| """ | |
| Get Redis client instance. | |
| Returns: | |
| redis.Redis: Redis client instance | |
| """ | |
| return redis_client | |