直接干货上代码
from loadbp import load_bp
app = Flask(__name__, template_folder="templates")
load_bp(app)
新增一个loadbp.py文件
import logging
import glob
import importlib
from flask import Blueprint, Flask
app = Flask(__name__)
area='yunnan'
module_path = f"./evcs/api/{area}/*.py"
def load_bp(app, path=module_path):
for file_path in glob.glob(path, recursive=True):
module_name = file_path.split(".")[1].replace("\\", ".").replace("/", ".")
module_name =str(module_name)[1:] if str(module_name).startswith('.') else module_name
try:
module = importlib.import_module(module_name)
if "__init__" in file_path:
continue
if hasattr(module, "_DO_NOT_LOAD_BP"):
logging.warn("ignore module %s because of attribute _DO_NOT_LOAD_BP settled", module_name)
continue
for attr_name in dir(module):
attr = getattr(module, attr_name)
if isinstance(attr, Blueprint):
logging.info("register %s to flask", attr_name)
print(attr)
app.register_blueprint(attr)
except AttributeError:
logging.error("failed to load module %s", module_name)
pass
如果有一些 Blueprint 暂时还不想加载,那么设置一个属性 _DO_NOT_LOAD_BP 放在你创建蓝图的py文件中即可
_DO_NOT_LOAD_BP = True