1+ from sqlalchemy import create_engine
2+ from sqlalchemy .ext .declarative import declarative_base
3+ from sqlalchemy .orm import sessionmaker
4+ from sqlalchemy .orm import scoped_session
5+ from sqlalchemy .ext .asyncio import create_async_engine , AsyncSession
6+ from sqlalchemy .ext .declarative import as_declarative
7+ from sqlalchemy .ext .asyncio import AsyncSession
8+
9+ import logging
10+ import os
11+ from typing import Any , Dict , Generator
12+ from fastapi .responses import JSONResponse
13+ from fastapi import Depends , HTTPException , status
14+
15+ from .config import settings
16+
17+
18+ logging .basicConfig (level = logging .INFO )
19+ logger = logging .getLogger (__name__ )
20+
21+ SQLALCHEMY_DATABASE_URL = os .environ .get ("DATABASE_URL" )
22+
23+ engine = create_engine (
24+ SQLALCHEMY_DATABASE_URL , pool_pre_ping = True , connect_args = {"check_same_thread" : False }
25+ )
26+
27+ SessionLocal = sessionmaker (autocommit = False , autoflush = False , bind = engine )
28+
29+ Base = declarative_base ()
30+
31+ async def get_async_session () -> Generator [AsyncSession , Any , None ]:
32+ async_engine = create_async_engine (SQLALCHEMY_DATABASE_URL , echo = True )
33+ async_session = sessionmaker (
34+ autocommit = False ,
35+ autoflush = False ,
36+ bind = async_engine ,
37+ class_ = AsyncSession ,
38+ )
39+ async with async_session () as session :
40+ yield session
41+
42+ async def get_db ():
43+ async with SessionLocal () as session :
44+ try :
45+ yield session
46+ finally :
47+ session .close ()
0 commit comments