forked from mtusi2026/mtusi2026lab2
reworked
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app import config
|
||||
from app.errors import AppError
|
||||
|
||||
client: redis.Redis | None = None
|
||||
|
||||
|
||||
async def connect() -> redis.Redis:
|
||||
global client
|
||||
client = redis.from_url(
|
||||
config.REDIS_URL,
|
||||
socket_connect_timeout=config.REDIS_SOCKET_TIMEOUT,
|
||||
socket_timeout=config.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, "service unavailable")
|
||||
return client
|
||||
|
||||
|
||||
async def ping() -> None:
|
||||
try:
|
||||
await require().ping()
|
||||
except AppError:
|
||||
raise
|
||||
except Exception:
|
||||
raise AppError(503, "service unavailable") from None
|
||||
Reference in New Issue
Block a user