Skip to content
Myr

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

5 files+154 added−56 removed

modified:docs/blueprints.rst+25 added
118 unmodified lines
119On 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/create142143Blueprint-specific before request functions, etc. registered with the144parent will trigger for the child. If a child does not have an error145handler that can handle a given exception, the parent's will be tried.146147148Blueprint Resources149-------------------150151Blueprints can provide resources as well. Sometimes you might want to
151 unmodified lines
modified:src/flask/app.py+31 added-43 removed
721 unmodified lines
722 """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 to
253 unmodified lines
986 accessed in :meth:`~flask.Blueprint.record` callbacks.987988 .. versionadded:: 0.7989 """990 first_registration = False990 blueprint.register(self, options)991992 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 = True10031004 blueprint.register(self, options, first_registration)1005992 def iter_blueprints(self):993 """Iterates over all blueprints by the order they were registered.994995 .. versionadded:: 0.11
224 unmodified lines
1220 class, or ``None`` if a suitable handler is not found.1221 """1222 exc_class, code = self._get_exc_class_and_code(type(e))12231238 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]12271246 if not handler_map:1247 continue1228 if not handler_map:1229 continue12301249 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)12331252 if handler is not None:1253 return handler1234 if handler is not None:1235 return handler12361237 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 the
490 unmodified lines
1730 value is handled as if it was the return value from the view, and1731 further request handling is stopped.1732 """17331752 bp = _request_ctx_stack.top.request.blueprint17531734 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)17401741 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 rv
11 unmodified lines
1760 :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 lines
1796 """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 lines
1966 WSGI application. This calls :meth:`wsgi_app`, which can be1967 wrapped to apply middleware.1968 """1969 return self.wsgi_app(environ, start_response)19701971 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 lines
44 #: The prefix that should be used for all URLs defined on the45 #: blueprint.46 self.url_prefix = url_prefix4748 self.name_prefix = self.options.get("name_prefix", "")4950 #: 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 lines
69 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 lines
169 url_defaults = {}170171 self.url_values_defaults = url_defaults172 self.cli_group = cli_group173 self._blueprints = []174175 def _is_setup_finished(self):176 return self.warn_on_modifications and self._got_registered_once177
34 unmodified lines
212 Subclasses can override this to return a subclass of the setup state.213 """214 return BlueprintSetupState(self, app, options, first_registration)215213 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.220221 .. versionadded:: 2.0222 """223 self._blueprints.append((blueprint, options))224225 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 lines
234 :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 = False239240 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 = True251252 self._got_registered_once = True253 state = self.make_setup_state(app, options, first_registration)254255 if self.has_static_folder:
47 unmodified lines
303304 for deferred in self.deferred_functions:305 deferred(state)306281 if not self.cli.commands:282 return283307 cli_resolved_group = options.get("cli_group", self.cli_group)308309 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)318319 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 )325326 bp_options["url_prefix"] = url_prefix327 bp_options["name_prefix"] = options.get("name_prefix", "") + self.name + "."328 blueprint.register(app, bp_options)329330 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 lines
modified:tests/test_blueprints.py+49 added
848 unmodified lines
849 app.register_blueprint(bp)850851 assert client.get("/de/").data == b"/de/about"852 assert client.get("/de/about").data == b"/de/"853854855def test_nested_blueprint(app, client):856 parent = flask.Blueprint("parent", __name__)857 child = flask.Blueprint("child", __name__)858 grandchild = flask.Blueprint("grandchild", __name__)859860 @parent.errorhandler(403)861 def forbidden(e):862 return "Parent no", 403863864 @parent.route("/")865 def parent_index():866 return "Parent yes"867868 @parent.route("/no")869 def parent_no():870 flask.abort(403)871872 @child.route("/")873 def child_index():874 return "Child yes"875876 @child.route("/no")877 def child_no():878 flask.abort(403)879880 @grandchild.errorhandler(403)881 def grandchild_forbidden(e):882 return "Grandchild no", 403883884 @grandchild.route("/")885 def grandchild_index():886 return "Grandchild yes"887888 @grandchild.route("/no")889 def grandchild_no():890 flask.abort(403)891892 child.register_blueprint(grandchild, url_prefix="/grandchild")893 parent.register_blueprint(child, url_prefix="/child")894 app.register_blueprint(parent, url_prefix="/parent")895896 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 lines
68 ``@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`737475Version 1.1.276-------------
1011 unmodified lines