39 lines
1.7 KiB
Python
39 lines
1.7 KiB
Python
# database.py
|
|
# 本文件负责配置数据库连接、创建引擎、会话工厂,并提供依赖注入函数
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
# 1. 配置 MySQL 数据库连接 URL
|
|
# 格式:mysql+pymysql://用户名:密码@主机:端口/数据库名?编码
|
|
# 请将下面的 'root', '123456', 'localhost', '3306', 'test_db' 替换为你自己的实际信息
|
|
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://root:123456@localhost:3306/max_code_sms"
|
|
|
|
# 2. 创建数据库引擎
|
|
# - pool_pre_ping=True 表示每次从连接池取出连接前先 ping 一下,防止使用已断开的连接
|
|
engine = create_engine(
|
|
SQLALCHEMY_DATABASE_URL,
|
|
pool_pre_ping=True,
|
|
echo=True # 设置为 True 会在控制台打印所有 SQL 语句,便于调试,生产环境可关闭
|
|
)
|
|
|
|
# 3. 创建会话工厂
|
|
# autocommit=False:不自动提交,需要手动 commit
|
|
# autoflush=False:不自动 flush,在查询前会自动 flush,一般保持默认
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# 4. 创建声明式基类,所有模型类都继承自它
|
|
Base = declarative_base()
|
|
|
|
# 5. 依赖注入函数:用于 FastAPI 路由中获取数据库会话
|
|
def get_db():
|
|
"""
|
|
每次请求创建一个数据库会话,请求结束后关闭。
|
|
这个函数会作为 Depends 的参数注入到路由中。
|
|
"""
|
|
db = SessionLocal() # 创建一个会话实例
|
|
try:
|
|
yield db # 将会话交给路由函数使用
|
|
finally:
|
|
db.close() # 无论是否发生异常,最后都会关闭会话,释放连接 |