49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
from functools import cache
|
|
|
|
import redis
|
|
import redis.asyncio as async_redis
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.engine import Engine
|
|
|
|
from config.main import BACKEND_DIR, config
|
|
|
|
# redis-py 8 defaults to RESP3. Keep the existing RESP2 wire contract so the
|
|
# client remains compatible with older Redis servers and proxies.
|
|
RedisPool = redis.ConnectionPool.from_url(config.REDIS_URL, protocol=2)
|
|
AsyncRedisPool = async_redis.ConnectionPool.from_url(config.REDIS_URL, protocol=2)
|
|
_db_engines: set[Engine] = set()
|
|
|
|
|
|
def get_redis_client():
|
|
return redis.Redis(connection_pool=RedisPool)
|
|
|
|
|
|
def get_redis():
|
|
with get_redis_client() as redis_conn:
|
|
yield redis_conn
|
|
|
|
|
|
async def get_async_redis():
|
|
redis_conn = async_redis.Redis(connection_pool=AsyncRedisPool)
|
|
try:
|
|
yield redis_conn
|
|
finally:
|
|
await redis_conn.aclose()
|
|
|
|
|
|
@cache
|
|
def get_db_engine(version='0'):
|
|
db_path = BACKEND_DIR / 'dataFiles' / f'dcalc_{version}.db'
|
|
engine = create_engine(f'sqlite:///{db_path}')
|
|
_db_engines.add(engine)
|
|
return engine
|
|
|
|
|
|
async def close_connection_pools() -> None:
|
|
RedisPool.close()
|
|
await AsyncRedisPool.aclose()
|
|
for engine in _db_engines:
|
|
engine.dispose()
|
|
_db_engines.clear()
|
|
get_db_engine.cache_clear()
|