appfactories.rst
This file
Path
docs/patterns/appfactories.rst
118 lines · 4.0 KiB
Last changed by
Merge pull request #5037 from pamelafox/patch-1David Lordbefore adoptiondaf6966
History of this fileTake it
The walk stopped after 200 commits: lines older than 41aaaf7 point at it.
clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
lines 1–91why, one step back1Application Factories2=====================34If you are already using packages and blueprints for your application5(:doc:`/blueprints`) there are a couple of really nice ways to further improve6the experience. A common pattern is creating the application object when7the blueprint is imported. But if you move the creation of this object8into a function, you can then create multiple instances of this app later.910So why would you want to do this?11121. Testing. You can have instances of the application with different13 settings to test every case.142. Multiple instances. Imagine you want to run different versions of the15 same application. Of course you could have multiple instances with16 different configs set up in your webserver, but if you use factories,17 you can have multiple instances of the same application running in the18 same application process which can be handy.1920So how would you then actually implement that?2122Basic Factories23---------------2425The idea is to set up the application in a function. Like this::2627 def create_app(config_filename):28 app = Flask(__name__)29 app.config.from_pyfile(config_filename)3031 from yourapplication.model import db32 db.init_app(app)3334 from yourapplication.views.admin import admin35 from yourapplication.views.frontend import frontend36 app.register_blueprint(admin)37 app.register_blueprint(frontend)3839 return app4041The downside is that you cannot use the application object in the blueprints42at import time. You can however use it from within a request. How do you43get access to the application with the config? Use44:data:`~flask.current_app`::4546 from flask import current_app, Blueprint, render_template47 admin = Blueprint('admin', __name__, url_prefix='/admin')4849 @admin.route('/')50 def index():51 return render_template(current_app.config['INDEX_TEMPLATE'])5253Here we look up the name of a template in the config.5455Factories & Extensions56----------------------5758It's preferable to create your extensions and app factories so that the59extension object does not initially get bound to the application.6061Using `Flask-SQLAlchemy <https://flask-sqlalchemy.palletsprojects.com/>`_,62as an example, you should not do something along those lines::6364 def create_app(config_filename):65 app = Flask(__name__)66 app.config.from_pyfile(config_filename)6768 db = SQLAlchemy(app)6970But, rather, in model.py (or equivalent)::7172 db = SQLAlchemy()7374and in your application.py (or equivalent)::7576 def create_app(config_filename):77 app = Flask(__name__)78 app.config.from_pyfile(config_filename)7980 from yourapplication.model import db81 db.init_app(app)8283Using this design pattern, no application-specific state is stored on the84extension object, so one extension object can be used for multiple apps.85For more information about the design of extensions refer to :doc:`/extensiondev`.8687Using Applications88------------------8990To run such an application, you can use the :command:`flask` command:91Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727
line 92why, one step back92.. code-block:: textclean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
line 93why, one step back93Merge branch '2.2.x'David Lordbefore adoption4ddb3f7
line 94why, one step back94 $ flask --app hello runclean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
line 95why, one step back95Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727
lines 96–98why, one step back96Flask will automatically detect the factory if it is named97``create_app`` or ``make_app`` in ``hello``. You can also pass arguments98to the factory like this:clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
line 99why, one step back99Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727
line 100why, one step back100.. code-block:: textclean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
line 101why, one step back101Merge pull request #5037 from pamelafox/patch-1David Lordbefore adoptiondaf6966
line 102why, one step back102 $ flask --app hello:create_app(local_auth=True) runclean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
line 103why, one step back103Merge pull request #4646 from pallets/cli-app-envDavid Lordbefore adoptionae54727
lines 104–105why, one step back104Then the ``create_app`` factory in ``myapp`` is called with the keyword105argument ``local_auth=True``. See :doc:`/cli` for more detail.clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7
lines 106–118why, one step back106107Factory Improvements108--------------------109110The factory function above is not very clever, but you can improve it.111The following changes are straightforward to implement:1121131. Make it possible to pass in configuration values for unit tests so that114 you don't have to create config files on the filesystem.1152. Call a function from a blueprint when the application is setting up so116 that you have a place to modify attributes of the application (like117 hooking in before/after request handlers etc.)1183. Add in WSGI middlewares when the application is being created if necessary.