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',
)
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__)
- 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']
- 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