How register Flask Blueprints from config like apps in Django?

和自甴很熟 提交于 2020-01-13 19:05:07

问题


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

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

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

回答1:


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.)

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 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)



回答2:


Flask is not Django, it doesn't have such features. If your really need this, you can try to implement this behaviour yourself:

Assume you have central Flask application file with:

import flask
app = flask.Flask(__name__)
  1. Put your BLUEPRINTS variable into flask's config (the one you register with app.config.from_pyfile(...)), so it will be accessible via app.config['BLUEPRINTS']
  2. In your central application file (where you do app=flask.Flask(__name__)), just iterate over app.config['BLUEPRINTS'], try to import them from the places where they can be, and register them with app.register_blueprint().


来源:https://stackoverflow.com/questions/11643680/how-register-flask-blueprints-from-config-like-apps-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!