finished
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
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", "Сервис временно недоступен")
|
||||
Reference in New Issue
Block a user