Flask自动加载Blueprint

栏目: Python · 发布时间: 6年前

内容简介:写多了是不是非常简单?如果有一些下面是实现:

写多了 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)

以上所述就是小编给大家介绍的《Flask自动加载Blueprint》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Mission Python

Mission Python

Sean McManus / No Starch Press / 2018-9-18 / GBP 24.99

Launch into coding with Mission Python, a space-themed guide to building a complete computer game in Python. You'll learn programming fundamentals like loops, strings, and lists as you build Escape!, ......一起来看看 《Mission Python》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

html转js在线工具
html转js在线工具

html转js在线工具