Skip to content
Myr

Started documentation for blueprints

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent b4ffa4d · Browse files · 4 files+94 added−30 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+94 added−30 removed

  • other:+94 added−30 removed

4 files+94 added−30 removed

added:docs/blueprints.rst+43 added
1.. _blueprints:23Modular Applications with Blueprints4====================================56.. versionadded:: 0.778Flask knows a concept known as “blueprints” which can greatly simplify how9large applications work. A blueprint is an object works similar to an10actual :class:`Flask` application object, but it is not actually an11application. Rather it is the blueprint of how to create an application.12Think of it like that: you might want to have an application that has a13wiki. So what you can do is creating the blueprint for a wiki and then14let the application assemble the wiki on the application object.1516Why Blueprints?17---------------1819Why have blueprints and not multiple application objects? The utopia of20pluggable applications are different WSGI applications and merging them21together somehow. You can do that (see :ref:`app-dispatch`) but it's not22the right tool for every case. Having different applications means having23different configs. Applications are also separated on the WSGI layer24which is a lot lower level than the level that Flask usually operates on25where you have request and response objects.2627Blueprints do not necessarily have to implement applications. They could28only provide filters for templates, static files, templates or similar29things. They share the same config as the application and can change the30application as necessary when being registered.3132The downside is that you cannot unregister a blueprint once application33without having to destroy the whole application object.3435The Concept of Blueprints36-------------------------3738The basic concept of blueprints is that they record operations that should39be executed when the blueprint is registered on the application. However40additionally each time a request gets dispatched to a view that was41declared to a blueprint Flask will remember that the request was42dispatched to that blueprint. That way it's easier to generate URLs from43one endpoint to another in the same module.
modified:docs/contents.rst.inc+1 added
16 unmodified lines
17 errorhandling18 config19 signals20 reqcontext21 blueprints22 shell23 patterns/index24 deploying/index25 becomingbig
29 unmodified lines
modified:flask/blueprints.py+36 added-17 removed
50 unmodified lines
5152 .. versionadded:: 0.753 """5455 warn_on_modifications = False56 _got_registered_once = False5758 def __init__(self, name, import_name, static_folder=None,59 static_url_path=None, url_prefix=None,60 subdomain=None):61 _PackageBoundObject.__init__(self, import_name)
4 unmodified lines
66 self.static_url_path = static_url_path67 self.deferred_functions = []68 self.view_functions = {}6967 def _record(self, func):70 def record(self, func):71 """Registers a function that is called when the blueprint is72 registered on the application. This function is called with the73 state as argument as returned by the :meth:`make_setup_state`74 method.75 """76 if self._got_registered_once and self.warn_on_modifications:77 from warnings import warn78 warn(Warning('The blueprint was already registered once '79 'but is getting modified now. These changes '80 'will not show up.'))81 self.deferred_functions.append(func)8270 def _record_once(self, func):83 def record_once(self, func):84 """Works like :meth:`record` but wraps the function in another85 function that will ensure the function is only called once. If the86 blueprint is registered a second time on the application, the87 function passed is not called.88 """89 def wrapper(state):90 if state.first_registration:91 func(state)74 return self._record(update_wrapper(wrapper, func))92 return self.record(update_wrapper(wrapper, func))9394 def make_setup_state(self, app, options, first_registration=False):95 return BlueprintSetupState(self, app, options, first_registration)96
3 unmodified lines
100 behavior. Keyword arguments from101 :func:`~flask.Flask.register_blueprint` are directly forwarded to this102 method in the `options` dictionary.103 """104 self._got_registered_once = True105 state = self.make_setup_state(app, options, first_registration)106 if self.has_static_folder:107 state.add_url_rule(self.static_url_path + '/<path:filename>',108 view_func=self.send_static_file,
14 unmodified lines
123 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):124 """Like :meth:`Flask.add_url_rule` but for a module. The endpoint for125 the :func:`url_for` function is prefixed with the name of the module.126 """108 self._record(lambda s:127 self.record(lambda s:128 s.add_url_rule(rule, endpoint, view_func, **options))129130 def endpoint(self, endpoint):131 """Like :meth:`Flask.endpoint` but for a module. This does not
4 unmodified lines
136 """137 def decorator(f):138 def register_endpoint(state):139 state.app.view_functions[endpoint] = f121 self._record_once(register_endpoint)140 self.record_once(register_endpoint)141 return f142 return decorator143144 def before_request(self, f):145 """Like :meth:`Flask.before_request` but for a module. This function146 is only executed before each request that is handled by a function of147 that module.148 """130 self._record_once(lambda s: s.app.before_request_funcs149 self.record_once(lambda s: s.app.before_request_funcs150 .setdefault(self.name, []).append(f))151 return f152153 def before_app_request(self, f):154 """Like :meth:`Flask.before_request`. Such a function is executed155 before each request, even if outside of a module.156 """138 self._record_once(lambda s: s.app.before_request_funcs157 self.record_once(lambda s: s.app.before_request_funcs158 .setdefault(None, []).append(f))159 return f160161 def after_request(self, f):162 """Like :meth:`Flask.after_request` but for a module. This function163 is only executed after each request that is handled by a function of164 that module.165 """147 self._record_once(lambda s: s.app.after_request_funcs166 self.record_once(lambda s: s.app.after_request_funcs167 .setdefault(self.name, []).append(f))168 return f169170 def after_app_request(self, f):171 """Like :meth:`Flask.after_request` but for a module. Such a function172 is executed after each request, even if outside of the module.173 """155 self._record_once(lambda s: s.app.after_request_funcs174 self.record_once(lambda s: s.app.after_request_funcs175 .setdefault(None, []).append(f))176 return f177178 def context_processor(self, f):179 """Like :meth:`Flask.context_processor` but for a module. This180 function is only executed for requests handled by a module.181 """163 self._record_once(lambda s: s.app.template_context_processors182 self.record_once(lambda s: s.app.template_context_processors183 .setdefault(self.name, []).append(f))184 return f185186 def app_context_processor(self, f):187 """Like :meth:`Flask.context_processor` but for a module. Such a188 function is executed each request, even if outside of the module.189 """171 self._record_once(lambda s: s.app.template_context_processors190 self.record_once(lambda s: s.app.template_context_processors191 .setdefault(None, []).append(f))192 return f193194 def app_errorhandler(self, code):195 """Like :meth:`Flask.errorhandler` but for a module. This196 handler is used for all requests, even if outside of the module.197 """198 def decorator(f):180 self._record_once(lambda s: s.app.errorhandler(code)(f))199 self.record_once(lambda s: s.app.errorhandler(code)(f))200 return f201 return decorator202203 def url_value_preprocessor(self, f):204 """Registers a function as URL value preprocessor for this205 blueprint. It's called before the view functions are called and206 can modify the url values provided.207 """189 self._record_once(lambda s: s.app.url_value_preprocessors208 self.record_once(lambda s: s.app.url_value_preprocessors209 .setdefault(self.name, []).append(f))210 return f211212 def url_defaults(self, f):213 """Callback function for URL defaults for this module. It's called214 with the endpoint and values and should update the values passed215 in place.216 """198 self._record_once(lambda s: s.app.url_default_functions217 self.record_once(lambda s: s.app.url_default_functions218 .setdefault(self.name, []).append(f))219 return f220221 def app_url_value_preprocessor(self, f):222 """Same as :meth:`url_value_preprocessor` but application wide.223 """205 self._record_once(lambda s: s.app.url_value_preprocessor224 self.record_once(lambda s: s.app.url_value_preprocessor225 .setdefault(self.name, []).append(f))226 return f227228 def app_url_defaults(self, f):229 """Same as :meth:`url_defaults` but application wide.230 """212 self._record_once(lambda s: s.app.url_default_functions231 self.record_once(lambda s: s.app.url_default_functions232 .setdefault(None, []).append(f))233 return f234235 def errorhandler(self, code_or_exception):
9 unmodified lines
245246 .. versionadded:: 0.7247 """248 def decorator(f):230 self._record_once(lambda s: s.app._register_error_handler(249 self.record_once(lambda s: s.app._register_error_handler(250 self.name, code_or_exception, f))251 return f252 return decorator
modified:scripts/testproj/test.py+14 added-13 removed
1from flask import Flask, Module1from flask import Flask, Module, render_template234mod = Module(__name__)5mod2 = Module(__name__, 'testmod2')6mod3 = Module(__name__, name='somemod', subdomain='meh')78app = Flask(__name__)9app.register_module(mod)10app.register_module(mod2)81213def handle_404(error):14 return 'Testing', 40415app.error_handlers[404] = handle_40416179@app.after_request10def after_request(response):11 g.db.close()12 return response
4 unmodified lines
17 return render_template('test/index.html')181920@mod2.route('/')30def index():21def mod2_index():22 return render_template('testmod2/index.html')232434@mod2.route('/')35def index():25@mod3.route('/')26def mod3_index():27 return render_template('something-else/index.html')282930app = Flask(__name__)31app.register_module(mod)32app.register_module(mod2)333435def handle_404(error):36 return 'Testing', 40437app.error_handlers[404] = handle_404