python flask项目 动态注册蓝图

def create_app():
    # 初始化app
    app = Flask(config.APP)

    # 初始化config
    app.config.from_object(config)

    blueprint_list = []
    path = os.path.dirname(os.path.abspath(__file__))
    file_list = os.listdir(path)
    for filename in file_list:
        file_path = os.path.join(path, filename)  # 连接path和文件名,这一行很有必要
        if os.path.isdir(file_path):  # 判断filepath路径是否是一个文件夹
            views_name = os.path.join(file_path, 'views.py')
            if os.path.exists(views_name):
                # print(file_path)
                blueprint_list.append(filename)

    console.info(blueprint_list)

    # 动态注册蓝图
    for blueprint in blueprint_list:
        auto_blueprint_module = importlib.import_module('app.' + blueprint)
        auto_blueprint = auto_blueprint_module.__dict__[blueprint]
        # from .query import query as query_blueprint
        app.register_blueprint(auto_blueprint, url_prefix=config.URL_PREFIX)

    return app

你可能感兴趣的:(python flask项目 动态注册蓝图)