-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
42 lines (29 loc) · 922 Bytes
/
database.py
File metadata and controls
42 lines (29 loc) · 922 Bytes
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
from contextlib import asynccontextmanager
from sqlalchemy import Column, Integer
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import declarative_base, declared_attr
from bot.core.settings import settings
class PreBase:
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
id = Column(Integer, primary_key=True)
Base = declarative_base(cls=PreBase)
engine = create_async_engine(settings.database_engine)
def async_session_generator():
return async_sessionmaker(engine, class_=AsyncSession)
@asynccontextmanager
async def async_session():
try:
get_async_session = async_session_generator()
async with get_async_session() as session:
yield session
except Exception:
await session.rollback()
raise
finally:
await session.close()