1. The most basic blueprint example.
from flask import Blueprint, render_template, abort from jinja2 import TemplateNotFound simple_page = Blueprint('simple_page', __name__, template_folder='templates') @simple_page.route('/', defaults={'page': 'index'}) @simple_page.route('/<page>') def show(page): return "response is ok"
#When you use @simple_page.route When the decorator binds a function, the blueprint will record the registered function show Function. When the blueprint is registered in the application in the future, this function will be registered in the application. In addition,
It will build Blueprint The name used when (in this case simple_page )Prefix the function endpoint. The name of the blueprint cannot be modified URL ,Modify only endpoints.
Blueprint Parameter explanationBlueprint( #Default parameters
name: str, #Blue picture name
import_name: str, #Where the blueprint is located'Package( package)'The name of helps locate the root path of the blueprint
static_folder: t.Optional[t.Union[str, os.PathLike]] = None, #Blueprint static file directory, disabled by default
#Manual assignment static_url_path When, if static_url_path Not an empty string, url The path must be/Beginning, such as/static
#Manually specify static_url_path, if static_ url_ The path is an empty string, and the URL path does not have to start with /. Otherwise, it is equivalent to static_url_path=None, that is, static is used_ Folder directory name.static_url_path: t.Optional[str] = None,
template_folder: t.Optional[str] = None,#Template path (relative path to blue chart)
url_prefix: t.Optional[str] = None, #Attached to all blueprints url Prefix of the path, equivalent to "route" = "url_prefix/Routing under blueprint
subdomain: t.Optional[str] = None,
url_defaults: t.Optional[dict] = None,#Blueprint routing default dictionary
root_path: t.Optional[str] = None,#Manually specify the root path of the blueprint
cli_group: t.Optional[str] = _sentinel, # type: ignore)
2. Registration blueprint
from flask import Flask from yourapplication.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page)
register_blueprint Introduction to method parametersregister_blueprint(blueprint,#Blueprint nameurl_prefix#Routing prefix)
3. Nested blueprints
Concept: register one blueprint on another
parent = Blueprint('parent', __name__, url_prefix='/parent') child = Blueprint('child', __name__, url_prefix='/child') parent.register_blueprint(child) app.register_blueprint(parent)
The child blueprint will prefix the name of the parent blueprint, and the child URL will also prefix the parent URL.
url_for('parent.child.create') /parent/child/create
The pre request function specified by the parent blueprint will be triggered for the child blueprint. If the child blueprint does not have an error handler that can handle exceptions, the error handling of the parent blueprint is attempted.
4 . Blueprint resources
Blueprints can also be used to provide resources. Sometimes we use blueprints just to use some resources
4.1 blueprint resource folder
Like normal applications, blueprints are generally placed in a folder. Although multiple blueprints can coexist in the same folder, it is best not to do so.
Folder by Blueprint The second parameter of, usually__ name__ . This parameter specifies the logical Python module or package associated with the blueprint. If this parameter refers to the actual Python package (a folder in the file system), it is the resource folder. If it is a module, the package contained in the module is the resource folder. You can Blueprint.root_path Property to view the resource folder of the blueprint:
simple_page.root_path '/Users/username/TestProject/yourapplication'
Can use open_resource() Function to quickly open resources in this folder:
with simple_page.open_resource('static/style.css') as f: code = f.read()
4.2 static files
The third parameter of the blueprint is static_folder . This parameter is used to specify the folder where the static files of the blueprint are located. It can be an absolute path or a relative path.:
admin = Blueprint('admin', __name__, static_folder='static')
By default, the rightmost part of the path is the part exposed in the URL. This can be done through static_url_path to change. Because the folder name in the above example is "static", the URL should be the "static" URL of the blueprint_ Prefix plus / static. If the blueprint registration prefix is / Admin, the static file URL is / admin/static.
The name of the endpoint is blue print_ name. static . You can use it like a folder in an application url_for() To generate its URL:
url_for('admin.static', filename='style.css')
However, if the blueprint does not have a url_prefix, then it is impossible to access the static folder of the blueprint. This is because in this case, the URL should be / static, and the / static route of the application takes precedence. Unlike the template folder, if the file does not exist in the application static folder, the blueprint static folder is not searched.
4.3 formwork
If you want to use blueprints to expose templates, you can use Blueprint Template for_ Folder} parameters:
admin = Blueprint('admin', __name__, template_folder='templates')
For static files, the path can be absolute or relative to the resource folder of the blue chart.
The template folder is added to the search path of the template, but the priority is lower than the actually applied template folder. In this way, you can easily reload the templates provided by the blueprint in practical application. This also means that if you don't want the blueprint template to be rewritten unexpectedly, make sure that no other blueprint or actual application template has the same relative path. When multiple blueprints provide the same relative path, the first registration takes precedence.
Suppose that the template to be rendered in your application / admin is' admin / index html' , template_ If the value of the folder , parameter is , templates, the real template file is: yourplication / admin / templates / admin / index html . One more "admin" folder is used to prevent the template from being actually applied to the "index" in the template folder HTML} overload.
To be more specific: if you have a blueprint named admin, the template file specified in the blueprint is index HTML, you'd better store the template file according to the following structure:
yourpackage/ blueprints/ admin/ templates/ admin/ index.html __init__.py
In this way, when you need to render a template, you can use admin / index HTML to find the template. If the correct template is not loaded, you should enable EXPLAIN_TEMPLATE_LOADING configuration variable. After enabling this variable, each time you call {render_ When template , flash will print out the steps to locate the template for debugging.
5. Create URL
If you want to create page links, you can use them as usual url_for() Function, just prefix the blueprint name as the endpoint and separate it with a dot (.):
url_for('admin.index')
In addition, if you need to link other endpoints in the same blueprint in the view function of a blueprint or the rendered template, use relative redirection. Only one point is used as the prefix:
url_for('.index')
If the current request is assigned to the admin blueprint endpoint, the above example will link to admin index .
6. Blueprint error processor
Blue image Flask The application object also supports the {errorhandler} decorator, so it is easy to use blueprint specific custom error pages.
The following is an example of "404 Page Not Found" exception:
@simple_page.errorhandler(404) def page_not_found(e): return render_template('pages/404.html')
Most error handlers work as expected. However, there is an alert involving 404 and 405 exception processors. These error handlers will only be triggered by an appropriate raise statement or invoked in another blueprint view to invoke abort. They do not trigger invalid URL access. This is because the blueprint does not "own" a specific URL space. When an invalid URL access occurs, the application instance cannot know which blueprint error processor should run. If you want to implement different error handling strategies based on the URL prefix, you can define them in the application layer using the request proxy object:
@app.errorhandler(404) @app.errorhandler(405) def _handle_api_error(ex): if request.path.startswith('/api/'): return jsonify(error=str(ex)), ex.code else: return ex