35 lines
862 B
Python
35 lines
862 B
Python
import json
|
|
|
|
import aioredis
|
|
from aioredis import Redis
|
|
from aioredis.client import ExpiryT
|
|
|
|
from core.config import DatabaseConfig
|
|
|
|
|
|
def redis_db(db: DatabaseConfig) -> Redis:
|
|
# Redis client bound to pool of connections (auto-reconnecting).
|
|
redis = aioredis.from_url(
|
|
db.url,
|
|
encoding="utf-8",
|
|
decode_responses=True,
|
|
db=int(db.db) or 0
|
|
)
|
|
return redis
|
|
|
|
|
|
async def redis_set(key: str, value: any, db: DatabaseConfig, ex=ExpiryT):
|
|
redis_c = redis_db(db)
|
|
await redis_c.set(key, json.dumps(value), ex=ex)
|
|
await redis_c.close()
|
|
return True
|
|
|
|
|
|
async def redis_get(key: str, db: DatabaseConfig):
|
|
redis_c = redis_db(db)
|
|
_return = await redis_c.get(key)
|
|
await redis_c.close()
|
|
if not _return or isinstance(_return, (int, float, complex)):
|
|
return _return
|
|
return json.loads(_return)
|