blueprints.rst
This file
Path
docs/blueprints.rst
315 lines · 12.3 KiB
Last changed by
Merge pull request #4935 from pgjones/subdomainDavid Lordbefore adoption836866d
History of this fileTake it
The walk stopped after 200 commits: lines older than 48ee204 point at it.
Merge pull request #4189 from mgu/feat/use-exclude-patterns-reloaderDavid Lordbefore adoption48ee204
lines 1–142why, one step back1Modular Applications with Blueprints2====================================34.. currentmodule:: flask56.. versionadded:: 0.778Flask uses a concept of *blueprints* for making application components and9supporting common patterns within an application or across applications.10Blueprints can greatly simplify how large applications work and provide a11central means for Flask extensions to register operations on applications.12A :class:`Blueprint` object works similarly to a :class:`Flask`13application object, but it is not actually an application. Rather it is a14*blueprint* of how to construct or extend an application.1516Why Blueprints?17---------------1819Blueprints in Flask are intended for these cases:2021* Factor an application into a set of blueprints. This is ideal for22 larger applications; a project could instantiate an application object,23 initialize several extensions, and register a collection of blueprints.24* Register a blueprint on an application at a URL prefix and/or subdomain.25 Parameters in the URL prefix/subdomain become common view arguments26 (with defaults) across all view functions in the blueprint.27* Register a blueprint multiple times on an application with different URL28 rules.29* Provide template filters, static files, templates, and other utilities30 through blueprints. A blueprint does not have to implement applications31 or view functions.32* Register a blueprint on an application for any of these cases when33 initializing a Flask extension.3435A blueprint in Flask is not a pluggable app because it is not actually an36application -- it's a set of operations which can be registered on an37application, even multiple times. Why not have multiple application38objects? You can do that (see :doc:`/patterns/appdispatch`), but your39applications will have separate configs and will be managed at the WSGI40layer.4142Blueprints instead provide separation at the Flask level, share43application config, and can change an application object as necessary with44being registered. The downside is that you cannot unregister a blueprint45once an application was created without having to destroy the whole46application object.4748The Concept of Blueprints49-------------------------5051The basic concept of blueprints is that they record operations to execute52when registered on an application. Flask associates view functions with53blueprints when dispatching requests and generating URLs from one endpoint54to another.5556My First Blueprint57------------------5859This is what a very basic blueprint looks like. In this case we want to60implement a blueprint that does simple rendering of static templates::6162 from flask import Blueprint, render_template, abort63 from jinja2 import TemplateNotFound6465 simple_page = Blueprint('simple_page', __name__,66 template_folder='templates')6768 @simple_page.route('/', defaults={'page': 'index'})69 @simple_page.route('/<page>')70 def show(page):71 try:72 return render_template(f'pages/{page}.html')73 except TemplateNotFound:74 abort(404)7576When you bind a function with the help of the ``@simple_page.route``77decorator, the blueprint will record the intention of registering the78function ``show`` on the application when it's later registered.79Additionally it will prefix the endpoint of the function with the80name of the blueprint which was given to the :class:`Blueprint`81constructor (in this case also ``simple_page``). The blueprint's name82does not modify the URL, only the endpoint.8384Registering Blueprints85----------------------8687So how do you register that blueprint? Like this::8889 from flask import Flask90 from yourapplication.simple_page import simple_page9192 app = Flask(__name__)93 app.register_blueprint(simple_page)9495If you check the rules registered on the application, you will find96these::9798 >>> app.url_map99 Map([<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,100 <Rule '/<page>' (HEAD, OPTIONS, GET) -> simple_page.show>,101 <Rule '/' (HEAD, OPTIONS, GET) -> simple_page.show>])102103The first one is obviously from the application itself for the static104files. The other two are for the `show` function of the ``simple_page``105blueprint. As you can see, they are also prefixed with the name of the106blueprint and separated by a dot (``.``).107108Blueprints however can also be mounted at different locations::109110 app.register_blueprint(simple_page, url_prefix='/pages')111112And sure enough, these are the generated rules::113114 >>> app.url_map115 Map([<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,116 <Rule '/pages/<page>' (HEAD, OPTIONS, GET) -> simple_page.show>,117 <Rule '/pages/' (HEAD, OPTIONS, GET) -> simple_page.show>])118119On top of that you can register blueprints multiple times though not every120blueprint might respond properly to that. In fact it depends on how the121blueprint is implemented if it can be mounted more than once.122123Nesting Blueprints124------------------125126It is possible to register a blueprint on another blueprint.127128.. code-block:: python129130 parent = Blueprint('parent', __name__, url_prefix='/parent')131 child = Blueprint('child', __name__, url_prefix='/child')132 parent.register_blueprint(child)133 app.register_blueprint(parent)134135The child blueprint will gain the parent's name as a prefix to its136name, and child URLs will be prefixed with the parent's URL prefix.137138.. code-block:: python139140 url_for('parent.child.create')141 /parent/child/create142Merge pull request #4935 from pgjones/subdomainDavid Lordbefore adoption836866d
lines 143–155why, one step back143In addition a child blueprint's will gain their parent's subdomain,144with their subdomain as prefix if present i.e.145146.. code-block:: python147148 parent = Blueprint('parent', __name__, subdomain='parent')149 child = Blueprint('child', __name__, subdomain='child')150 parent.register_blueprint(child)151 app.register_blueprint(parent)152153 url_for('parent.child.create', _external=True)154 "child.parent.domain.tld"155Merge pull request #4189 from mgu/feat/use-exclude-patterns-reloaderDavid Lordbefore adoption48ee204
lines 156–315why, one step back156Blueprint-specific before request functions, etc. registered with the157parent will trigger for the child. If a child does not have an error158handler that can handle a given exception, the parent's will be tried.159160161Blueprint Resources162-------------------163164Blueprints can provide resources as well. Sometimes you might want to165introduce a blueprint only for the resources it provides.166167Blueprint Resource Folder168`````````````````````````169170Like for regular applications, blueprints are considered to be contained171in a folder. While multiple blueprints can originate from the same folder,172it does not have to be the case and it's usually not recommended.173174The folder is inferred from the second argument to :class:`Blueprint` which175is usually `__name__`. This argument specifies what logical Python176module or package corresponds to the blueprint. If it points to an actual177Python package that package (which is a folder on the filesystem) is the178resource folder. If it's a module, the package the module is contained in179will be the resource folder. You can access the180:attr:`Blueprint.root_path` property to see what the resource folder is::181182 >>> simple_page.root_path183 '/Users/username/TestProject/yourapplication'184185To quickly open sources from this folder you can use the186:meth:`~Blueprint.open_resource` function::187188 with simple_page.open_resource('static/style.css') as f:189 code = f.read()190191Static Files192````````````193194A blueprint can expose a folder with static files by providing the path195to the folder on the filesystem with the ``static_folder`` argument.196It is either an absolute path or relative to the blueprint's location::197198 admin = Blueprint('admin', __name__, static_folder='static')199200By default the rightmost part of the path is where it is exposed on the201web. This can be changed with the ``static_url_path`` argument. Because the202folder is called ``static`` here it will be available at the203``url_prefix`` of the blueprint + ``/static``. If the blueprint204has the prefix ``/admin``, the static URL will be ``/admin/static``.205206The endpoint is named ``blueprint_name.static``. You can generate URLs207to it with :func:`url_for` like you would with the static folder of the208application::209210 url_for('admin.static', filename='style.css')211212However, if the blueprint does not have a ``url_prefix``, it is not213possible to access the blueprint's static folder. This is because the214URL would be ``/static`` in this case, and the application's ``/static``215route takes precedence. Unlike template folders, blueprint static216folders are not searched if the file does not exist in the application217static folder.218219Templates220`````````221222If you want the blueprint to expose templates you can do that by providing223the `template_folder` parameter to the :class:`Blueprint` constructor::224225 admin = Blueprint('admin', __name__, template_folder='templates')226227For static files, the path can be absolute or relative to the blueprint228resource folder.229230The template folder is added to the search path of templates but with a lower231priority than the actual application's template folder. That way you can232easily override templates that a blueprint provides in the actual application.233This also means that if you don't want a blueprint template to be accidentally234overridden, make sure that no other blueprint or actual application template235has the same relative path. When multiple blueprints provide the same relative236template path the first blueprint registered takes precedence over the others.237238239So if you have a blueprint in the folder ``yourapplication/admin`` and you240want to render the template ``'admin/index.html'`` and you have provided241``templates`` as a `template_folder` you will have to create a file like242this: :file:`yourapplication/admin/templates/admin/index.html`. The reason243for the extra ``admin`` folder is to avoid getting our template overridden244by a template named ``index.html`` in the actual application template245folder.246247To further reiterate this: if you have a blueprint named ``admin`` and you248want to render a template called :file:`index.html` which is specific to this249blueprint, the best idea is to lay out your templates like this::250251 yourpackage/252 blueprints/253 admin/254 templates/255 admin/256 index.html257 __init__.py258259And then when you want to render the template, use :file:`admin/index.html` as260the name to look up the template by. If you encounter problems loading261the correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config262variable which will instruct Flask to print out the steps it goes through263to locate templates on every ``render_template`` call.264265Building URLs266-------------267268If you want to link from one page to another you can use the269:func:`url_for` function just like you normally would do just that you270prefix the URL endpoint with the name of the blueprint and a dot (``.``)::271272 url_for('admin.index')273274Additionally if you are in a view function of a blueprint or a rendered275template and you want to link to another endpoint of the same blueprint,276you can use relative redirects by prefixing the endpoint with a dot only::277278 url_for('.index')279280This will link to ``admin.index`` for instance in case the current request281was dispatched to any other admin blueprint endpoint.282283284Blueprint Error Handlers285------------------------286287Blueprints support the ``errorhandler`` decorator just like the :class:`Flask`288application object, so it is easy to make Blueprint-specific custom error289pages.290291Here is an example for a "404 Page Not Found" exception::292293 @simple_page.errorhandler(404)294 def page_not_found(e):295 return render_template('pages/404.html')296297Most errorhandlers will simply work as expected; however, there is a caveat298concerning handlers for 404 and 405 exceptions. These errorhandlers are only299invoked from an appropriate ``raise`` statement or a call to ``abort`` in another300of the blueprint's view functions; they are not invoked by, e.g., an invalid URL301access. This is because the blueprint does not "own" a certain URL space, so302the application instance has no way of knowing which blueprint error handler it303should run if given an invalid URL. If you would like to execute different304handling strategies for these errors based on URL prefixes, they may be defined305at the application level using the ``request`` proxy object::306307 @app.errorhandler(404)308 @app.errorhandler(405)309 def _handle_api_error(ex):310 if request.path.startswith('/api/'):311 return jsonify(error=str(ex)), ex.code312 else:313 return ex314315See :doc:`/errorhandling`.