toxic-detector/app/core/cache.py

40 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import asyncio
import json
import hashlib
import logging
from typing import Optional
import redis.asyncio as aioredis
from app.core.config import settings
logger = logging.getLogger(__name__)
class RedisCache:
def __init__(self):
self.redis: Optional[aioredis.Redis] = None
async def connect(self):
if not self.redis:
self.redis = aioredis.from_url(settings.REDIS_URL, encoding="utf-8", decode_responses=True)
logger.info("Подключение к Redis установлено.")
async def disconnect(self):
if self.redis:
await self.redis.close()
logger.info("Подключение к Redis закрыто.")
async def get(self, key: str):
if not self.redis:
await self.connect()
value = await self.redis.get(key)
logger.debug(f"Получено из кеша по ключу {key}: {value}")
return value
async def set(self, key: str, value: str, expire: int = 3600):
if not self.redis:
await self.connect()
await self.redis.set(key, value, ex=expire)
logger.debug(f"Сохранено в кеш по ключу {key}: {value} с истечением {expire} секунд")
cache = RedisCache()