init
This commit is contained in:
6
server/app/db/base.py
Normal file
6
server/app/db/base.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""SQLAlchemy ORM Base。"""
|
||||
|
||||
36
server/app/db/session.py
Normal file
36
server/app/db/session.py
Normal file
@@ -0,0 +1,36 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
|
||||
def create_engine():
|
||||
"""
|
||||
创建异步 Engine。
|
||||
|
||||
注意:连接串从环境变量 `DATABASE_URL` 读取。
|
||||
"""
|
||||
|
||||
settings = get_settings()
|
||||
return create_async_engine(settings.database_url, pool_pre_ping=True)
|
||||
|
||||
|
||||
engine = create_engine()
|
||||
|
||||
AsyncSessionLocal: async_sessionmaker[AsyncSession] = async_sessionmaker(
|
||||
bind=engine,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
autocommit=False,
|
||||
)
|
||||
|
||||
|
||||
async def get_db() -> AsyncSession:
|
||||
"""
|
||||
FastAPI 依赖:获取数据库会话。
|
||||
"""
|
||||
|
||||
async with AsyncSessionLocal() as session:
|
||||
yield session
|
||||
|
||||
Reference in New Issue
Block a user