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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
| from contextlib import asynccontextmanager,contextmanager
from typing import AsyncIterator, Iterator
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from sqlalchemy import AsyncAdaptedQueuePool, create_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import Session
from sqlmodel.ext.asyncio.session import AsyncSession
async_engine = create_async_engine(
async_url, # 异步dsn postgresql+asyncpg://
echo=app.settings.ECHO,
future=True,
pool_size=2,
max_overflow=30,
pool_recycle=3600,
pool_pre_ping=True,
poolclass=AsyncAdaptedQueuePool,
)
AsyncSessionLocal = async_sessionmaker(
bind=async_engine,
class_=AsyncSession,
expire_on_commit=False, # 避免commit后属性过期
)
@asynccontextmanager
async def get_async_session() -> AsyncIterator[AsyncSession]:
""" """
async with AsyncSessionLocal() as session:
yield session
await session.commit()
sync_engine = create_engine(
sync_url, # postgresql+psycopg2://
echo=app.settings.ECHO,
pool_size=2,
max_overflow=30,
pool_recycle=3600,
pool_pre_ping=True,
)
SyncSessionLocal = sessionmaker(
bind=sync_engine,
class_=Session,
expire_on_commit=False, # 避免commit后属性过期
)
@contextmanager
def get_sync_session()->Iterator[Session]:
with SyncSessionLocal() as session:
yield session
session.commit()
def session_scope(func):
"""会话管理装饰器(自动开启、提交、回滚、关闭会话)"""
@wraps(func)
def wrapper(*args, **kwargs):
with SyncSessionLocal() as session:
try:
result = func(*args, session_=session, **kwargs)
session.commit()
return result
except Exception as e:
session.rollback()
raise e
return wrapper
|