Application Factories

    So why would you want to do this?

    • Testing. You can have instances of the application with differentsettings to test every case.

    So how would you then actually implement that?

    The idea is to set up the application in a function. Like this:

    1. from flask import current_app, Blueprint, render_template
    2. admin = Blueprint('admin', __name__, url_prefix='/admin')
    3.  
    4. @admin.route('/')
    5. def index():

    Here we look up the name of a template in the config.

    It’s preferable to create your extensions and app factories so that theextension object does not initially get bound to the application.

    Using Flask-SQLAlchemy,as an example, you should not do something along those lines:

    But, rather, in model.py (or equivalent):

    1. db = SQLAlchemy()

    and in your application.py (or equivalent):

    To run such an application, you can use the flask command:

    1. $ export FLASK_APP=myapp
    2. $ flask run

    Flask will automatically detect the factory (create_app or )in myapp. You can also pass arguments to the factory like this:

    Then the factory in myapp is called with the string as the argument. See for more detail.

    The factory function above is not very clever, but you can improve it.The following changes are straightforward to implement:

    • Make it possible to pass in configuration values for unit tests so thatyou don’t have to create config files on the filesystem.