xxy aa98ea2623 @
Initial commit

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@
2026-06-05 18:45:29 +08:00

43 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
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, # 提交后对象仍可访问属性,便于返回响应
)