Flask自动加载Blueprint

写多了 from controllers.xxx import xxx, app.register_blueprint(xxx) 就想偷懒。 于是就仿照 unittest 的实现思路来做了一个自动加载 Blueprint 的工具。使用方法如下:

from loadbp import load_bp

app = Flask(__name__, template_folder="templates")
load_bp(app)

是不是非常简单?如果有一些 Blueprint 暂时还不想加载,那么设置一个属性 _DO_NOT_LOAD_BP 即可。例如:

$ grep _DO_NOT_LOAD_BP controllers/*
controllers/issue.py:_DO_NOT_LOAD_BP = True
controllers/user.py:_DO_NOT_LOAD_BP = True

下面是实现:

import logging
import glob
import importlib

from flask import Blueprint, Flask

app = Flask(__name__)


def load_bp(app, path="controllers/**/*.py"):
    for file_path in glob.glob(path, recursive=True):
        module_name = file_path.split(".")[0].replace("/", ".")
        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)
                    app.register_blueprint(attr)
        except AttributeError:
            logging.error("failed to load module %s", module_name)


更多文章
  • Clash 结合 工作VPN 的网络设计
  • 使用 PostgreSQL 搭建 JuiceFS
  • PostgreSQL 配置优化和日志分析
  • 有GitHub Copilot?那就可以搭建你的ChatGPT4服务
  • 窗口函数的使用(以PG为例)
  • 读《为什么学生不喜欢上学》
  • OpenAI Prompt Engineering 摘录和总结
  • 读《打造真正的新产品》
  • 2023年终总结
  • VueJS 总结
  • Linux 自动挂载 alist 提供的webdav
  • FreeBSD 使用 vm-bhyve 安装Debian虚拟机
  • FreeBSD 和 Linux 网卡聚合实现提速
  • GPT 帮我搞定了时区转换问题
  • 长任务系统如何处理?