-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.py
49 lines (39 loc) · 1.4 KB
/
config.py
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
39
40
41
42
43
44
45
46
47
48
49
import os
from dotenv import load_dotenv
from sqlmodel import SQLModel
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
load_dotenv()
DB_CONFIG = os.getenv('DB_CONFIG')
class DatabaseSession:
def __init__(self,url:str=DB_CONFIG):
self.engine = create_async_engine(url,echo=True)
self.SessionLocal = sessionmaker(
bind=self.engine,
class_=AsyncSession,
expire_on_commit=False
)
# Generating models into a database
async def create_all(self):
async with self.engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
async def drop_all(self):
async with self.engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.drop_all)
# close connection
async def close(self):
await self.engine.dispose()
# Prepare the context for the asynchronous operation
async def __aenter__(self) -> AsyncSession:
self.session = self.SessionLocal()
return self.session
# It is used to clean up resources, etc
async def __aexit__(self,exc_type,exc_val,exc_tb):
await self.session.close()
async def commit_rollback(self):
try:
await self.session.commit()
except Exception:
await self.session.rollback()
raise
db = DatabaseSession()