| 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:
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. |
|