diff --git a/app/core/config.py b/app/core/config.py index c569d05e..5d80cec2 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -1,10 +1,9 @@ import secrets -from urllib.parse import urlparse - import sys import threading from pathlib import Path from typing import Optional, List +from urllib.parse import urlparse from pydantic import BaseSettings, validator @@ -41,6 +40,20 @@ class Settings(BaseSettings): DEBUG: bool = False # 是否开发模式 DEV: bool = False + # 是否在控制台输出 SQL 语句,默认关闭 + DB_ECHO: bool = False + # 是否在获取连接时进行预先 ping 操作,默认开启 + DB_POOL_PRE_PING: bool = True + # 数据库连接池的大小,默认 100 + DB_POOL_SIZE: int = 100 + # 数据库连接的回收时间(秒),默认 3600 秒(1 小时) + DB_POOL_RECYCLE: int = 3600 + # 数据库连接池获取连接的超时时间(秒),默认 180 秒 + DB_POOL_TIMEOUT: int = 180 + # 数据库连接池最大溢出连接数,默认 5 + DB_MAX_OVERFLOW: int = 5 + # SQLite 的 busy_timeout 参数,默认为 60 秒 + DB_TIMEOUT: int = 60 # 配置文件目录 CONFIG_DIR: Optional[str] = None # 超级管理员 diff --git a/app/db/__init__.py b/app/db/__init__.py index 2ecd065c..cb62c197 100644 --- a/app/db/__init__.py +++ b/app/db/__init__.py @@ -1,25 +1,27 @@ import json -from typing import Any, Self, List -from typing import Tuple, Optional, Generator +from typing import Any, Self, List, Tuple, Optional, Generator -from sqlalchemy import create_engine, QueuePool, and_ -from sqlalchemy import inspect -from sqlalchemy.orm import declared_attr -from sqlalchemy.orm import sessionmaker, Session, scoped_session, as_declarative +from sqlalchemy import create_engine, QueuePool, and_, inspect +from sqlalchemy.orm import declared_attr, sessionmaker, Session, scoped_session, as_declarative from app.core.config import settings from app.utils.object import ObjectUtils # 数据库引擎 -Engine = create_engine(f"sqlite:///{settings.CONFIG_PATH}/user.db", - pool_pre_ping=True, - echo=False, - poolclass=QueuePool, - pool_size=1024, - pool_recycle=3600, - pool_timeout=180, - max_overflow=10, - connect_args={"timeout": 60}) +Engine = create_engine( + url=f"sqlite:///{settings.CONFIG_PATH}/user.db", + pool_pre_ping=settings.DB_POOL_PRE_PING, + echo=settings.DB_ECHO, + poolclass=QueuePool, + pool_size=settings.DB_POOL_SIZE, + pool_recycle=settings.DB_POOL_RECYCLE, + pool_timeout=settings.DB_POOL_TIMEOUT, + max_overflow=settings.DB_MAX_OVERFLOW, + connect_args={ + "timeout": settings.DB_TIMEOUT + } +) + # 会话工厂 SessionFactory = sessionmaker(bind=Engine) diff --git a/config/app.env b/config/app.env index a0213757..812e6a85 100644 --- a/config/app.env +++ b/config/app.env @@ -7,6 +7,12 @@ HOST=0.0.0.0 DEBUG=false # 是否开发模式,打开后后台服务将不会启动 DEV=false +# 数据库连接池的大小,可适当降低如10-50以减少I/O压力 +DB_POOL_SIZE=100 +# 数据库连接池最大溢出连接数,可适当降低如0以减少I/O压力 +DB_MAX_OVERFLOW=5 +# SQLite 的 busy_timeout 参数,可适当增加如180以减少锁定错误 +DB_TIMEOUT=60 # 【*】超级管理员,设置后一但重启将固化到数据库中,修改将无效(初始化超级管理员密码仅会生成一次,请在日志中查看并自行登录系统修改) SUPERUSER=admin # 大内存模式,开启后会增加缓存数量,但会占用更多内存