1.

Explain Application Factories in terms of Blueprints in the Flask application.

Answer»

There are a few of really good ways to improve the experience if you're already utilizing packages and blueprints for your APPLICATION (MODULAR Applications with Blueprints). When the blueprint is imported, a common PATTERN is to create the application object. You can make additional copies of this app later if you move the creation of this object into a function.

So, why would you want to do something like this?

  • Testing: To test each example, you can create many instances of the PROGRAM with varied configurations.
  • There are multiple occurrences: Consider the scenario when you wish to run many versions of the same program. Of course, you could set up numerous instances in your web server with various configurations, but if you utilize factories, you can have multiple instances of the same application running in the same application process, which is useful.

So, how would you go about putting that into practice? Well, the idea is to set up the application in a function which we call Application Factories

def create_app(config_filename):[Text Wrapping Break]    app = Flask(__name__)[Text Wrapping Break]    app.config.from_pyfile(config_filename)[Text Wrapping Break][Text Wrapping Break]    from yourapplication.model import db[Text Wrapping Break]    db.init_app(app)[Text Wrapping Break][Text Wrapping Break]    from yourapplication.views.admin import admin[Text Wrapping Break]    from yourapplication.views.frontend import frontend[Text Wrapping Break]    app.register_blueprint(admin)[Text Wrapping Break]    app.register_blueprint(frontend)[Text Wrapping Break][Text Wrapping Break]    return app

The disadvantage is that you can't use the application object in blueprints when they're being imported. However, you can utilize it within a REQUEST. With the config, how do you gain access to the application? Make use of current_app:\

from flask import current_app, Blueprint, render_template[Text Wrapping Break]admin = Blueprint('admin', __name__, url_prefix='/admin')[Text Wrapping Break][Text Wrapping Break]@admin.route('/')[Text Wrapping Break]def index():[Text Wrapping Break]    return render_template(current_app.config['INDEX_TEMPLATE'])


Discussion

No Comment Found