如何注册配置像Django的应用程序Flask Blueprints? [英] How register Flask Blueprints from config like apps in Django?

查看:131
本文介绍了如何注册配置像Django的应用程序Flask Blueprints?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在配置文件中定义Blueprints,这个配置文件会被自动注册

How I can register Flask Blueprints from my config like apps in Django?

如何从Django的应用程序注册Flask Blueprints? p>

I would like to define Blueprints in the configuration file, which will be automatically registered

#config.py
BLUEPRINTS = (
'news',
'files',
)


推荐答案

就像一个名为兜里的项目。这与@HighCat给出的答案基本相同,只是它使用Python的打包系统而不是 config.py 文件(虽然它可以扩展为从配置文件自动加载相反 - and 拉请求是最受欢迎的。)

I actually have been sketching out something like that in a project tentatively named Hip Pocket. It's basically the same answer as @HighCat has given you, except it uses Python's packaging system rather than a config.py file (although it could be extended to autoload from a config file instead - issues and pull requests are most welcome.)

所以在Hip Pocket你会这样做(见 hip_pocket.tasks 它工作):

So in Hip Pocket you'd do this (see hip_pocket.tasks for how it works):

from flask import Flask
from hip_pocket.tasks import autoload

app = Flask(__name__)
autoload(app)

autoload (code> apps_package )来查找的程序包(默认情况下命名为apps,不过您可以通过传递关键字arg apps_package c> flask.Blueprint 要注册的对象应用程序(默认情况下它会在它找到的每个子包中的名为 routes 的模块中查找名为 routes 这些默认设置也可以改变。)您的文件夹布局可能看起来像这样:

autoload walks a package (named "apps" by default, although you can change it by passing in the keyword arg apps_package) looking for flask.Blueprint objects to register on the application (by default it looks for a symbol named routes in a module named routes in each sub package it finds but those defaults can be changed as well.) Your folder layout might look like this:

+ you_app
. . . . __init__.py
. . . . app.py
. . . . + apps
        . . . . __init__.py
        . . . . routes.py # contains the declaration `routes = Blueprint(...)`
        . . . . + news
                . . . . __init__.py
                . . . . routes.py     # Ditto
                . . . . some_module.py
        . . . . + files
                . . . . __init__.py
                . . . . routes.py     # Ditto
                . . . . # etc.

或者,如果您想使用基于配置的加载程序,则可以这样做:

Alternately, if you want to use a config based loader, you could just do this:

 from flask import Flask
 from werkzeug.utils import import_string

 app = Flask(__name__)
 app.config.from_object("your_app.config")

 for tool_path in app.config["BLUEPRINTS"]:
     tool = import_string(tool_path)
     app.register_blueprint(tool)

这篇关于如何注册配置像Django的应用程序Flask Blueprints?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆