Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 240 lines (177 sloc) 9.472 kB
bfd6776 @mitsuhiko Started documentation for blueprints
authored
1 .. _blueprints:
2
3 Modular Applications with Blueprints
4 ====================================
5
6cd54a4 @mitsuhiko Fixed some cross linking in the docs
authored
6 .. currentmodule:: flask
7
bfd6776 @mitsuhiko Started documentation for blueprints
authored
8 .. versionadded:: 0.7
9
0313c8b @rduplain Expand documentation on blueprints.
rduplain authored
10 Flask uses a concept of *blueprints* for making application components and
11 supporting common patterns within an application or across applications.
12 Blueprints can greatly simplify how large applications work and provide a
13 central means for Flask extensions to register operations on applications.
14 A :class:`Blueprint` object works similarly to a :class:`Flask`
15 application object, but it is not actually an application. Rather it is a
16 *blueprint* of how to construct or extend an application.
bfd6776 @mitsuhiko Started documentation for blueprints
authored
17
18 Why Blueprints?
19 ---------------
20
0313c8b @rduplain Expand documentation on blueprints.
rduplain authored
21 Blueprints in Flask are intended for these cases:
bfd6776 @mitsuhiko Started documentation for blueprints
authored
22
0313c8b @rduplain Expand documentation on blueprints.
rduplain authored
23 * Factor an application into a set of blueprints. This is ideal for
24 larger applications; a project could instantiate an application object,
25 initialize several extensions, and register a collection of blueprints.
26 * Register a blueprint on an application at a URL prefix and/or subdomain.
e2fed6c @mitsuhiko Fixed another typo
authored
27 Parameters in the URL prefix/subdomain become common view arguments
0313c8b @rduplain Expand documentation on blueprints.
rduplain authored
28 (with defaults) across all view functions in the blueprint.
29 * Register a blueprint multiple times on an application with different URL
30 rules.
31 * Provide template filters, static files, templates, and other utilities
32 through blueprints. A blueprint does not have to implement applications
33 or view functions.
34 * Register a blueprint on an application for any of these cases when
35 initializing a Flask extension.
bfd6776 @mitsuhiko Started documentation for blueprints
authored
36
0313c8b @rduplain Expand documentation on blueprints.
rduplain authored
37 A blueprint in Flask is not a pluggable app because it is not actually an
38 application -- it's a set of operations which can be registered on an
39 application, even multiple times. Why not have multiple application
40 objects? You can do that (see :ref:`app-dispatch`), but your applications
41 will have separate configs and will be managed at the WSGI layer.
42
43 Blueprints instead provide separation at the Flask level, share
44 application config, and can change an application object as necessary with
45 being registered. The downside is that you cannot unregister a blueprint
de3b6ab @mitsuhiko Fixed a broken sentence about blueprints.
authored
46 once an application was created without having to destroy the whole
47 application object.
bfd6776 @mitsuhiko Started documentation for blueprints
authored
48
49 The Concept of Blueprints
50 -------------------------
51
0313c8b @rduplain Expand documentation on blueprints.
rduplain authored
52 The basic concept of blueprints is that they record operations to execute
53 when registered on an application. Flask associates view functions with
54 blueprints when dispatching requests and generating URLs from one endpoint
55 to another.
2647bec @mitsuhiko Added a minimal blueprint example
authored
56
57 My First Blueprint
58 ------------------
59
60 This is what a very basic blueprint looks like. In this case we want to
61 implement a blueprint that does simple rendering of static templates::
62
63 from flask import Blueprint, render_template, abort
64 from jinja2 import TemplateNotFound
65
04bb720 @rduplain Fix Blueprint example with template_folder, #403.
rduplain authored
66 simple_page = Blueprint('simple_page', __name__,
67 template_folder='templates')
2647bec @mitsuhiko Added a minimal blueprint example
authored
68
69 @simple_page.route('/', defaults={'page': 'index'})
70 @simple_page.route('/<page>')
71 def show(page):
72 try:
59a92eb @mitsuhiko Updated blueprint documentation
authored
73 return render_template('pages/%s.html' % page)
2647bec @mitsuhiko Added a minimal blueprint example
authored
74 except TemplateNotFound:
75 abort(404)
59a92eb @mitsuhiko Updated blueprint documentation
authored
76
77 When you bind a function with the help of the ``@simple_page.route``
78 decorator the blueprint will record the intention of registering the
79 function `show` on the application when it's later registered.
80 Additionally it will prefix the endpoint of the function with the
81 name of the blueprint which was given to the :class:`Blueprint`
82 constructor (in this case also ``simple_page``).
83
dbfa04e @mitsuhiko Removed old module documentation and added some new for blueprints.
authored
84 Registering Blueprints
85 ----------------------
86
59a92eb @mitsuhiko Updated blueprint documentation
authored
87 So how do you register that blueprint? Like this::
88
89 from flask import Flask
90 from yourapplication.simple_page import simple_page
91
92 app = Flask(__name__)
93 app.register_blueprint(simple_page)
94
95 If you check the rules registered on the application, you will find
96 these::
97
98 [<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
99 <Rule '/<page>' (HEAD, OPTIONS, GET) -> simple_page.show>,
100 <Rule '/' (HEAD, OPTIONS, GET) -> simple_page.show>]
101
bd888ea @bulatb Fixed a typo.
bulatb authored
102 The first one is obviously from the application itself for the static
59a92eb @mitsuhiko Updated blueprint documentation
authored
103 files. The other two are for the `show` function of the ``simple_page``
104 blueprint. As you can see, they are also prefixed with the name of the
105 blueprint and separated by a dot (``.``).
106
dbfa04e @mitsuhiko Removed old module documentation and added some new for blueprints.
authored
107 Blueprints however can also be mounted at different locations::
108
109 app.register_blueprint(simple_page, url_prefix='/pages')
110
111 And sure enough, these are the generated rules::
112
113 [<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
114 <Rule '/pages/<page>' (HEAD, OPTIONS, GET) -> simple_page.show>,
115 <Rule '/pages/' (HEAD, OPTIONS, GET) -> simple_page.show>]
116
117 On top of that you can register blueprints multiple times though not every
118 blueprint might respond properly to that. In fact it depends on how the
119 blueprint is implemented if it can be mounted more than once.
120
59a92eb @mitsuhiko Updated blueprint documentation
authored
121 Blueprint Resources
122 -------------------
123
124 Blueprints can provide resources as well. Sometimes you might want to
125 introduce a blueprint only for the resources it provides.
126
127 Blueprint Resource Folder
128 `````````````````````````
129
130 Like for regular applications, blueprints are considered to be contained
5f367e8 @pingswept Fix typos.
pingswept authored
131 in a folder. While multiple blueprints can originate from the same folder,
59a92eb @mitsuhiko Updated blueprint documentation
authored
132 it does not have to be the case and it's usually not recommended.
133
5f367e8 @pingswept Fix typos.
pingswept authored
134 The folder is inferred from the second argument to :class:`Blueprint` which
135 is usually `__name__`. This argument specifies what logical Python
59a92eb @mitsuhiko Updated blueprint documentation
authored
136 module or package corresponds to the blueprint. If it points to an actual
137 Python package that package (which is a folder on the filesystem) is the
138 resource folder. If it's a module, the package the module is contained in
139 will be the resource folder. You can access the
5f367e8 @pingswept Fix typos.
pingswept authored
140 :attr:`Blueprint.root_path` property to see what the resource folder is::
59a92eb @mitsuhiko Updated blueprint documentation
authored
141
142 >>> simple_page.root_path
143 '/Users/username/TestProject/yourapplication'
144
145 To quickly open sources from this folder you can use the
146 :meth:`~Blueprint.open_resource` function::
147
148 with simple_page.open_resource('static/style.css') as f:
149 code = f.read()
150
151 Static Files
152 ````````````
153
154 A blueprint can expose a folder with static files by providing a path to a
155 folder on the filesystem via the `static_folder` keyword argument. It can
156 either be an absolute path or one relative to the folder of the
157 blueprint::
158
159 admin = Blueprint('admin', __name__, static_folder='static')
160
161 By default the rightmost part of the path is where it is exposed on the
a8f570c @defuz docs: :file:`app.py`, :file:`yourapp/templates`
defuz authored
162 web. Because the folder is called :file:`static` here it will be available at
59a92eb @mitsuhiko Updated blueprint documentation
authored
163 the location of the blueprint + ``/static``. Say the blueprint is
164 registered for ``/admin`` the static folder will be at ``/admin/static``.
165
166 The endpoint is named `blueprint_name.static` so you can generate URLs to
167 it like you would do to the static folder of the application::
168
169 url_for('admin.static', filename='style.css')
170
171 Templates
172 `````````
173
174 If you want the blueprint to expose templates you can do that by providing
175 the `template_folder` parameter to the :class:`Blueprint` constructor::
176
177 admin = Blueprint('admin', __name__, template_folder='templates')
178
179 As for static files, the path can be absolute or relative to the blueprint
62d91d6 @mitsuhiko More documentation updates
authored
180 resource folder. The template folder is added to the searchpath of
181 templates but with a lower priority than the actual application's template
182 folder. That way you can easily override templates that a blueprint
183 provides in the actual application.
184
185 So if you have a blueprint in the folder ``yourapplication/admin`` and you
186 want to render the template ``'admin/index.html'`` and you have provided
187 ``templates`` as a `template_folder` you will have to create a file like
a8f570c @defuz docs: :file:`app.py`, :file:`yourapp/templates`
defuz authored
188 this: :file:`yourapplication/admin/templates/admin/index.html`.
62d91d6 @mitsuhiko More documentation updates
authored
189
bafc139 @mitsuhiko Added EXPLAIN_TEMPLATE_LOADING to help people debug templates not bei…
authored
190 To further reiterate this: if you have a blueprint named ``admin`` and you
a8f570c @defuz docs: :file:`app.py`, :file:`yourapp/templates`
defuz authored
191 want to render a template called :file:`index.html` which is specific to this
bafc139 @mitsuhiko Added EXPLAIN_TEMPLATE_LOADING to help people debug templates not bei…
authored
192 blueprint, the best idea is to lay out your templates like this::
193
194 yourpackage/
195 blueprints/
196 admin/
197 templates/
198 admin/
199 index.html
200 __init__.py
201
a8f570c @defuz docs: :file:`app.py`, :file:`yourapp/templates`
defuz authored
202 And then when you want to render the template, use :file:`admin/index.html` as
bafc139 @mitsuhiko Added EXPLAIN_TEMPLATE_LOADING to help people debug templates not bei…
authored
203 the name to look up the template by. If you encounter problems loading
204 the correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config
205 variable which will instruct Flask to print out the steps it goes through
206 to locate templates on every ``render_template`` call.
207
62d91d6 @mitsuhiko More documentation updates
authored
208 Building URLs
209 -------------
210
211 If you want to link from one page to another you can use the
212 :func:`url_for` function just like you normally would do just that you
213 prefix the URL endpoint with the name of the blueprint and a dot (``.``)::
214
215 url_for('admin.index')
216
217 Additionally if you are in a view function of a blueprint or a rendered
218 template and you want to link to another endpoint of the same blueprint,
219 you can use relative redirects by prefixing the endpoint with a dot only::
220
221 url_for('.index')
222
223 This will link to ``admin.index`` for instance in case the current request
224 was dispatched to any other admin blueprint endpoint.
63a126c @hntw Update blueprints.rst - Error Handlers
hntw authored
225
226 Error Handlers
227 --------------
228
229 Blueprints support the errorhandler decorator just like the :class:`Flask`
230 application object, so it is easy to make Blueprint-specific custom error
231 pages.
232
233 Here is an example for a "404 Page Not Found" exception::
234
235 @simple_page.errorhandler(404)
236 def page_not_found(e):
237 return render_template('pages/404.html')
238
239 More information on error handling see :ref:`errorpages`.
Something went wrong with that request. Please try again.