优化
This commit is contained in:
+27
-11
@@ -1,11 +1,17 @@
|
||||
from functools import cache
|
||||
|
||||
import redis
|
||||
import redis.asyncio as async_redis
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.pool import NullPool
|
||||
from sqlalchemy.engine import Engine
|
||||
|
||||
from config.main import BACKEND_DIR, config
|
||||
|
||||
RedisPool = redis.ConnectionPool.from_url(config.REDIS_URL)
|
||||
# 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():
|
||||
@@ -17,16 +23,26 @@ def get_redis():
|
||||
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'
|
||||
return create_engine(
|
||||
f'sqlite:///{db_path}',
|
||||
connect_args={'check_same_thread': False},
|
||||
poolclass=NullPool,
|
||||
)
|
||||
engine = create_engine(f'sqlite:///{db_path}')
|
||||
_db_engines.add(engine)
|
||||
return engine
|
||||
|
||||
|
||||
def get_db():
|
||||
with Session(get_db_engine()) as session:
|
||||
yield session
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user