Merge pull request #3923 from pgjones/nested
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Nested blueprints
authored by David Lord · committed by GitHub · parents 85dce2c, f92e820 · Browse files · 5 files·+154 added−56 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+154 added−56 removed
- tests:+49 added−0 removed
- other:+105 added−56 removed
Provenance
- Commit
64213fc- Tree
9638cde- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
85dce2c- Parent 2
f92e820
5 files changed+154 added−56 removed
modified:docs/blueprints.rst+25 added
118 unmodified lines119 On top of that you can register blueprints multiple times though not every120 blueprint might respond properly to that. In fact it depends on how the121 blueprint is implemented if it can be mounted more than once.122 123+Nesting Blueprints124+------------------125+126+It is possible to register a blueprint on another blueprint.127+128+.. code-block:: python129+130+ 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)134+135+The child blueprint will gain the parent's name as a prefix to its136+name, and child URLs will be prefixed with the parent's URL prefix.137+138+.. code-block:: python139+140+ url_for('parent.child.create')141+ /parent/child/create142+143+Blueprint-specific before request functions, etc. registered with the144+parent will trigger for the child. If a child does not have an error145+handler that can handle a given exception, the parent's will be tried.146+147+148 Blueprint Resources149 -------------------150 151 Blueprints can provide resources as well. Sometimes you might want to151 unmodified linesmodified:src/flask/app.py+31 added-43 removed
721 unmodified lines722 """723 funcs = self.template_context_processors[None]724 reqctx = _request_ctx_stack.top725 if reqctx is not None:726- bp = reqctx.request.blueprint727- if bp is not None and bp in self.template_context_processors:728- funcs = chain(funcs, self.template_context_processors[bp])726+ for bp in self._request_blueprints():727+ if bp in self.template_context_processors:728+ funcs = chain(funcs, self.template_context_processors[bp])729 orig_ctx = context.copy()730 for func in funcs:731 context.update(func())732 # make sure the original values win. This makes it possible to253 unmodified lines986 accessed in :meth:`~flask.Blueprint.record` callbacks.987 988 .. versionadded:: 0.7989 """990- first_registration = False990+ blueprint.register(self, options)991 992- if blueprint.name in self.blueprints:993- assert self.blueprints[blueprint.name] is blueprint, (994- "A name collision occurred between blueprints"995- f" {blueprint!r} and {self.blueprints[blueprint.name]!r}."996- f" Both share the same name {blueprint.name!r}."997- f" Blueprints that are created on the fly need unique"998- f" names."999- )1000- else:1001- self.blueprints[blueprint.name] = blueprint1002- first_registration = True1003-1004- blueprint.register(self, options, first_registration)1005-992 def iter_blueprints(self):993 """Iterates over all blueprints by the order they were registered.994 995 .. versionadded:: 0.11224 unmodified lines1220 class, or ``None`` if a suitable handler is not found.1221 """1222 exc_class, code = self._get_exc_class_and_code(type(e))1223 1238- for name, c in (1239- (request.blueprint, code),1240- (None, code),1241- (request.blueprint, None),1242- (None, None),1243- ):1244- handler_map = self.error_handler_spec[name][c]1224+ for c in [code, None]:1225+ for name in chain(self._request_blueprints(), [None]):1226+ handler_map = self.error_handler_spec[name][c]1227 1246- if not handler_map:1247- continue1228+ if not handler_map:1229+ continue1230 1249- for cls in exc_class.__mro__:1250- handler = handler_map.get(cls)1231+ for cls in exc_class.__mro__:1232+ handler = handler_map.get(cls)1233 1252- if handler is not None:1253- return handler1234+ if handler is not None:1235+ return handler1236 1237 def handle_http_exception(self, e):1238 """Handles an HTTP exception. By default this will invoke the1239 registered error handlers and fall back to returning the490 unmodified lines1730 value is handled as if it was the return value from the view, and1731 further request handling is stopped.1732 """1733 1752- bp = _request_ctx_stack.top.request.blueprint1753-1734 funcs = self.url_value_preprocessors[None]1735+ for bp in self._request_blueprints():1755- if bp is not None and bp in self.url_value_preprocessors:1756- funcs = chain(funcs, self.url_value_preprocessors[bp])1736+ if bp in self.url_value_preprocessors:1737+ funcs = chain(funcs, self.url_value_preprocessors[bp])1738 for func in funcs:1739 func(request.endpoint, request.view_args)1740 1741 funcs = self.before_request_funcs[None]1742+ for bp in self._request_blueprints():1761- if bp is not None and bp in self.before_request_funcs:1762- funcs = chain(funcs, self.before_request_funcs[bp])1743+ if bp in self.before_request_funcs:1744+ funcs = chain(funcs, self.before_request_funcs[bp])1745 for func in funcs:1746 rv = func()1747 if rv is not None:1748 return rv11 unmodified lines1760 :return: a new response object or the same, has to be an1761 instance of :attr:`response_class`.1762 """1763 ctx = _request_ctx_stack.top1782- bp = ctx.request.blueprint1764 funcs = ctx._after_request_functions1765+ for bp in self._request_blueprints():1784- if bp is not None and bp in self.after_request_funcs:1785- funcs = chain(funcs, reversed(self.after_request_funcs[bp]))1766+ if bp in self.after_request_funcs:1767+ funcs = chain(funcs, reversed(self.after_request_funcs[bp]))1768 if None in self.after_request_funcs:1769 funcs = chain(funcs, reversed(self.after_request_funcs[None]))1770 for handler in funcs:1771 response = handler(response)24 unmodified lines1796 """1797 if exc is _sentinel:1798 exc = sys.exc_info()[1]1799 funcs = reversed(self.teardown_request_funcs[None])1818- bp = _request_ctx_stack.top.request.blueprint1819- if bp is not None and bp in self.teardown_request_funcs:1820- funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1800+ for bp in self._request_blueprints():1801+ if bp in self.teardown_request_funcs:1802+ funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1803 for func in funcs:1804 func(exc)1805 request_tearing_down.send(self, exc=exc)1806 159 unmodified lines1966 WSGI application. This calls :meth:`wsgi_app`, which can be1967 wrapped to apply middleware.1968 """1969 return self.wsgi_app(environ, start_response)1970+1971+ def _request_blueprints(self):1972+ if _request_ctx_stack.top.request.blueprint is None:1973+ return []1974+ else:1975+ return reversed(_request_ctx_stack.top.request.blueprint.split("."))modified:src/flask/blueprints.py+48 added-13 removed
43 unmodified lines44 #: The prefix that should be used for all URLs defined on the45 #: blueprint.46 self.url_prefix = url_prefix47 48+ self.name_prefix = self.options.get("name_prefix", "")49+50 #: A dictionary with URL defaults that is added to each and every51 #: URL that was defined with the blueprint.52 self.url_defaults = dict(self.blueprint.url_values_defaults)53 self.url_defaults.update(self.options.get("url_defaults", ()))15 unmodified lines69 if "defaults" in options:70 defaults = dict(defaults, **options.pop("defaults"))71 self.app.add_url_rule(72 rule,71- f"{self.blueprint.name}.{endpoint}",73+ f"{self.name_prefix}{self.blueprint.name}.{endpoint}",74 view_func,75 defaults=defaults,76 **options,77 )91 unmodified lines169 url_defaults = {}170 171 self.url_values_defaults = url_defaults172 self.cli_group = cli_group173+ self._blueprints = []174 175 def _is_setup_finished(self):176 return self.warn_on_modifications and self._got_registered_once177 34 unmodified lines212 Subclasses can override this to return a subclass of the setup state.213 """214 return BlueprintSetupState(self, app, options, first_registration)215 213- def register(self, app, options, first_registration=False):216+ def register_blueprint(self, blueprint, **options):217+ """Register a :class:`~flask.Blueprint` on this blueprint. Keyword218+ arguments passed to this method will override the defaults set219+ on the blueprint.220+221+ .. versionadded:: 2.0222+ """223+ self._blueprints.append((blueprint, options))224+225+ def register(self, app, options):226 """Called by :meth:`Flask.register_blueprint` to register all227 views and callbacks registered on the blueprint with the228 application. Creates a :class:`.BlueprintSetupState` and calls229 each :meth:`record` callbackwith it.4 unmodified lines234 :meth:`~Flask.register_blueprint`.235 :param first_registration: Whether this is the first time this236 blueprint has been registered on the application.237 """238+ first_registration = False239+240+ if self.name in app.blueprints:241+ assert app.blueprints[self.name] is self, (242+ "A name collision occurred between blueprints"243+ f" {self!r} and {app.blueprints[self.name]!r}."244+ f" Both share the same name {self.name!r}."245+ f" Blueprints that are created on the fly need unique"246+ f" names."247+ )248+ else:249+ app.blueprints[self.name] = self250+ first_registration = True251+252 self._got_registered_once = True253 state = self.make_setup_state(app, options, first_registration)254 255 if self.has_static_folder:47 unmodified lines303 304 for deferred in self.deferred_functions:305 deferred(state)306 281- if not self.cli.commands:282- return283-307 cli_resolved_group = options.get("cli_group", self.cli_group)308 309+ if self.cli.commands:286- if cli_resolved_group is None:287- app.cli.commands.update(self.cli.commands)288- elif cli_resolved_group is _sentinel:289- self.cli.name = self.name290- app.cli.add_command(self.cli)291- else:292- self.cli.name = cli_resolved_group293- app.cli.add_command(self.cli)310+ if cli_resolved_group is None:311+ app.cli.commands.update(self.cli.commands)312+ elif cli_resolved_group is _sentinel:313+ self.cli.name = self.name314+ app.cli.add_command(self.cli)315+ else:316+ self.cli.name = cli_resolved_group317+ app.cli.add_command(self.cli)318 319+ for blueprint, bp_options in self._blueprints:320+ url_prefix = options.get("url_prefix", "")321+ if "url_prefix" in bp_options:322+ url_prefix = (323+ url_prefix.rstrip("/") + "/" + bp_options["url_prefix"].lstrip("/")324+ )325+326+ bp_options["url_prefix"] = url_prefix327+ bp_options["name_prefix"] = options.get("name_prefix", "") + self.name + "."328+ blueprint.register(app, bp_options)329+330 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):331 """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for332 the :func:`url_for` function is prefixed with the name of the blueprint.333 """185 unmodified linesmodified:tests/test_blueprints.py+49 added
848 unmodified lines849 app.register_blueprint(bp)850 851 assert client.get("/de/").data == b"/de/about"852 assert client.get("/de/about").data == b"/de/"853+854+855+def test_nested_blueprint(app, client):856+ parent = flask.Blueprint("parent", __name__)857+ child = flask.Blueprint("child", __name__)858+ grandchild = flask.Blueprint("grandchild", __name__)859+860+ @parent.errorhandler(403)861+ def forbidden(e):862+ return "Parent no", 403863+864+ @parent.route("/")865+ def parent_index():866+ return "Parent yes"867+868+ @parent.route("/no")869+ def parent_no():870+ flask.abort(403)871+872+ @child.route("/")873+ def child_index():874+ return "Child yes"875+876+ @child.route("/no")877+ def child_no():878+ flask.abort(403)879+880+ @grandchild.errorhandler(403)881+ def grandchild_forbidden(e):882+ return "Grandchild no", 403883+884+ @grandchild.route("/")885+ def grandchild_index():886+ return "Grandchild yes"887+888+ @grandchild.route("/no")889+ def grandchild_no():890+ flask.abort(403)891+892+ child.register_blueprint(grandchild, url_prefix="/grandchild")893+ parent.register_blueprint(child, url_prefix="/child")894+ app.register_blueprint(parent, url_prefix="/parent")895+896+ assert client.get("/parent/").data == b"Parent yes"897+ assert client.get("/parent/child/").data == b"Child yes"898+ assert client.get("/parent/child/grandchild/").data == b"Grandchild yes"899+ assert client.get("/parent/no").data == b"Parent no"900+ assert client.get("/parent/child/no").data == b"Parent no"901+ assert client.get("/parent/child/grandchild/no").data == b"Grandchild no"modified:CHANGES.rst+1 added
67 unmodified lines68 ``@app.post("/login")`` is a shortcut for69 ``@app.route("/login", methods=["POST"])``. :pr:`3907`70 - Support async views, error handlers, before and after request, and71 teardown functions. :pr:`3412`72+- Support nesting blueprints. :issue:`593, 1548`, :pr:`3923`73 74 75 Version 1.1.276 -------------1011 unmodified lines