1.

What are Blueprints and why do we use them? Create a Blueprint in Flask.

Answer»

For creating application components and enabling common patterns within and between applications, Flask employs the concept of blueprints. Blueprints can help huge applications run more smoothly by PROVIDING a central location for Flask extensions to register activities on them. A Blueprint object is comparable to a Flask application object in functionality, but it is not one. It's more of a template on how to build or enhance an application.

Blueprints in Flask are designed for the following scenarios:

  • A set of blueprints can be used to factor an application. This is suitable for larger applications; a project may CREATE an application object, register a collection of blueprints, and initialize many extensions.
  • Register a blueprint with a URL prefix and/or subdomain on an application. All VIEW functions in the blueprint use parameters from the URL prefix/subdomain as common view arguments (with defaults).
  • Register a blueprint on an application numerous times with different URL rules each time.
  • By using blueprints, you can provide template filters, static files, TEMPLATES, and other tools. It is not necessary for a blueprint to implement applications or view functions.
  • When initializing a Flask extension, register a blueprint on an application for any of these scenarios.

This is an example of a very basic blueprint. In this scenario, we'd like to create a blueprint that renders static templates simply:

from flask import Blueprint, render_template, abort[Text WRAPPING Break]from jinja2 import TemplateNotFound[Text Wrapping Break][Text Wrapping Break]simple_page = Blueprint('simple_page', __name__,[Text Wrapping Break]                        template_folder='templates')[Text Wrapping Break][Text Wrapping Break]@simple_page.route('/', defaults={'page': 'index'})[Text Wrapping Break]@simple_page.route('/<page>')[Text Wrapping Break]def show(page):[Text Wrapping Break]    try:[Text Wrapping Break]        return render_template(f'pages/{page}.html')[Text Wrapping Break]    except TemplateNotFound:[Text Wrapping Break]        abort(404)

When you use the @simple_page.route decorator to bind a function, the blueprint records your intent to have the function show up on the app when it's later registered. In addition, the endpoint of the method will be prefixed with the name of the blueprint that was sent to the Blueprint constructor (in this case, simple_page). The name of the blueprint does not change the URL, simply the endpoint.



Discussion

No Comment Found