How register Flask Blueprints from config like apps in Django?

霸气de小男生 提交于 2019-12-06 02:37:24

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)

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