From 0214beb6798f161623bf294266b1121040e83a41 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Mon, 4 Dec 2023 11:33:16 +0800 Subject: [PATCH] =?UTF-8?q?-=20=E4=BF=AE=E5=A4=8D=E4=BA=8C=E8=BF=9B?= =?UTF-8?q?=E5=88=B6=E6=89=93=E5=8C=85=E6=8F=92=E4=BB=B6=E8=A1=A8=E7=BC=BA?= =?UTF-8?q?=E5=A4=B1=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/db/init.py | 5 +++-- app/helper/module.py | 24 ++++++++++++++++++++++++ version.py | 2 +- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/app/db/init.py b/app/db/init.py index acc70ab0..d21b1090 100644 --- a/app/db/init.py +++ b/app/db/init.py @@ -9,6 +9,7 @@ from app.core.security import get_password_hash from app.db import Engine, SessionFactory from app.db.models import Base from app.db.models.user import User +from app.helper.module import ModuleHelper from app.log import logger @@ -17,8 +18,8 @@ def init_db(): 初始化数据库 """ # 导入模块,避免建表缺失 - for module in Path(__file__).with_name("models").glob("*.py"): - importlib.import_module(f"app.db.models.{module.stem}") + models_path = Path(__file__).with_name("models") + ModuleHelper.dynamic_import_all_modules(models_path, "app.db.models") # 全量建表 Base.metadata.create_all(bind=Engine) # 初始化超级管理员 diff --git a/app/helper/module.py b/app/helper/module.py index ee911904..f0e9ba6e 100644 --- a/app/helper/module.py +++ b/app/helper/module.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- import importlib import pkgutil +from pathlib import Path class ModuleHelper: @@ -35,3 +36,26 @@ class ModuleHelper: print(f'加载模块 {package_name} 失败:{err}') return submodules + + @staticmethod + def dynamic_import_all_modules(base_path: Path, package_name: str): + """ + 动态导入所有模块到全局对象 + """ + modules = [] + # 遍历文件夹,找到所有模块文件 + for file in base_path.glob("*.py"): + file_name = file.stem + if file_name != "__init__": + modules.append(file_name) + # 保存已有的全局对象 + existing_globals = set(globals().keys()) + # 动态导入并添加到全局命名空间 + for module in modules: + full_module_name = f"{package_name}.{module}" + import_module = importlib.import_module(full_module_name) + module_globals = import_module.__dict__ + # 仅导入全局对象中不存在的部分 + new_objects = {name: value for name, value in module_globals.items() if name not in existing_globals} + # 更新全局命名空间 + globals().update(new_objects) diff --git a/version.py b/version.py index 034a378f..36be3e77 100644 --- a/version.py +++ b/version.py @@ -1 +1 @@ -APP_VERSION = 'v1.4.8' +APP_VERSION = 'v1.4.8-1'