45 lines
1.1 KiB
Python
45 lines
1.1 KiB
Python
import redis.asyncio as redis
|
|
|
|
from .config import settings
|
|
from .errors import AppError
|
|
|
|
client: redis.Redis | None = None
|
|
|
|
|
|
async def connect() -> redis.Redis:
|
|
global client
|
|
client = redis.from_url(
|
|
settings.redis_url,
|
|
socket_connect_timeout=settings.redis_socket_timeout,
|
|
socket_timeout=settings.redis_socket_timeout,
|
|
decode_responses=True,
|
|
)
|
|
await client.ping()
|
|
return client
|
|
|
|
|
|
async def close() -> None:
|
|
global client
|
|
if client is not None:
|
|
await client.close()
|
|
client = None
|
|
|
|
|
|
def require() -> redis.Redis:
|
|
if client is None:
|
|
raise AppError(503, "unavailable", "Сервис временно недоступен")
|
|
return client
|
|
|
|
|
|
async def ping() -> None:
|
|
try:
|
|
await require().ping()
|
|
except AppError:
|
|
raise
|
|
except Exception:
|
|
raise AppError(503, "unavailable", "Сервис временно недоступен") from None
|
|
|
|
|
|
def wrap_redis_errors(exc: Exception) -> AppError:
|
|
return AppError(503, "unavailable", "Сервис временно недоступен")
|