Search code examples
pythondjango-appsflask

How register Flask Blueprints from config like apps in Django?


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

Solution

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