Spaces:
Runtime error
Runtime error
File size: 1,144 Bytes
b64aabb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import os
import threading
from contextlib import asynccontextmanager
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
class DatabaseConfig:
_thread_local = threading.local()
@classmethod
def get_engine(cls):
if not hasattr(cls._thread_local, "engine"):
cls._thread_local.engine = create_async_engine(
url=os.getenv("SQLALCHEMY_DATABASE_URI"),
pool_pre_ping=True,
pool_recycle=3600,
)
return cls._thread_local.engine
@classmethod
def _get_session_factory(cls):
if not hasattr(cls._thread_local, "session_factory"):
cls._thread_local.session_factory = async_sessionmaker(
bind=cls.get_engine(),
autoflush=False,
autocommit=False,
expire_on_commit=False,
)
return cls._thread_local.session_factory
@classmethod
@asynccontextmanager
async def async_session(cls):
session_factory = cls._get_session_factory()
async with session_factory() as session:
yield session
|