43 lines
1.3 KiB
Python
43 lines
1.3 KiB
Python
"""
|
||
database/core.py
|
||
SQLAlchemy 引擎与 Session 工厂。
|
||
|
||
- 同步引擎,默认连接池(QueuePool)
|
||
- 后续可替换为 create_async_engine 实现异步
|
||
"""
|
||
|
||
from sqlalchemy import create_engine
|
||
from sqlalchemy.orm import sessionmaker, Session
|
||
|
||
from config import settings
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# 引擎配置
|
||
# -----------------------------------------------------------------------------
|
||
|
||
engine = create_engine(
|
||
settings.DATABASE_URL,
|
||
pool_size=settings.DB_POOL_SIZE,
|
||
max_overflow=settings.DB_MAX_OVERFLOW,
|
||
pool_timeout=settings.DB_POOL_TIMEOUT,
|
||
pool_pre_ping=settings.DB_POOL_PRE_PING,
|
||
pool_recycle=3600, # 1 小时回收空闲连接,避免 MySQL wait_timeout
|
||
connect_args={
|
||
"charset": "utf8mb4",
|
||
"use_unicode": True,
|
||
"init_command": "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
|
||
},
|
||
echo=False, # 开发时可设为 True 打印 SQL
|
||
)
|
||
|
||
# -----------------------------------------------------------------------------
|
||
# Session 工厂
|
||
# -----------------------------------------------------------------------------
|
||
|
||
SessionLocal = sessionmaker(
|
||
bind=engine,
|
||
autocommit=False,
|
||
autoflush=False,
|
||
expire_on_commit=False, # 提交后对象仍可访问属性,便于返回响应
|
||
)
|