Files
zkxw/backend/app/core/database.py
T
cykjandCursor f50c55f7b6 fix(ops): 降低 SQL/请求日志噪声并改善 500 恢复
SQL 回显与 DEBUG 解耦;API 请求日志按字节截断并失败降级;可恢复初始化错误不永久锁死,500 页可重试;修复生产任务 in_ 多余 subquery;补充本地登录态清理页。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-12-01 17:58:49 +08:00

37 lines
1.2 KiB
Python

from sqlalchemy import create_engine, event
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
engine = create_engine(
settings.DATABASE_URL,
pool_pre_ping=True,
pool_recycle=3600,
echo=settings.SQLALCHEMY_ECHO,
)
# 避免 commit 后 ORM 实例自动过期,导致读取字段时回表 SELECT(高频接口会显著拖慢)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, expire_on_commit=False, bind=engine)
Base = declarative_base()
def get_db():
"""获取数据库会话"""
db = SessionLocal()
try:
yield db
finally:
db.close()
@event.listens_for(Base, "before_insert", propagate=True)
def _auto_fill_create_dept_id(mapper, connection, target):
"""ORM before_insert 钩子:当 create_dept_id 为空时,自动从请求上下文填充当前用户部门 ID"""
if hasattr(target, "create_dept_id") and not getattr(target, "create_dept_id", None):
from app.core.context import current_user_dept_id
dept_id = current_user_dept_id.get("")
if dept_id:
target.create_dept_id = dept_id