Skip to content
Myr

Bugfix blueprint naming

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

Following discussions for Flask we've decided to name blueprints based on how they are registered. This allows for two different blueprints to have the same self-name as long as they are registered in different nested positions. This helps users choose better blueprint names.

authored by pgjones · committed by pgjones · parent 99afbb2 · Browse files · 3 files+50 added−33 removed
This commit

State

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

Diff stats

3 files+50 added−33 removed

  • other:+50 added−33 removed

3 files+50 added−33 removed

modified:src/flask/app.py+15 added-14 removed
745 unmodified lines
746 TemplateContextProcessorCallable747 ] = self.template_context_processors[None]748 reqctx = _request_ctx_stack.top749 if reqctx is not None:750 for bp in self._request_blueprints():750 for bp in request.blueprints:751 if bp in self.template_context_processors:752 funcs = chain(funcs, self.template_context_processors[bp])753 orig_ctx = context.copy()754 for func in funcs:
511 unmodified lines
1266 """1267 exc_class, code = self._get_exc_class_and_code(type(e))12681269 for c in [code, None]:1270 for name in chain(self._request_blueprints(), [None]):1270 for name in chain(request.blueprints, [None]):1271 handler_map = self.error_handler_spec[name][c]12721273 if not handler_map:1274 continue
512 unmodified lines
17871788 .. versionadded:: 0.71789 """1790 funcs: t.Iterable[URLDefaultCallable] = self.url_default_functions[None]17911792 if "." in endpoint:1792 bp = endpoint.rsplit(".", 1)[0]1793 funcs = chain(funcs, self.url_default_functions[bp])1793 bps: t.List[str] = [endpoint.rsplit(".", 1)[0]]17941795 while "." in bps[-1]:1796 bps.append(bps[-1].rpartition(".")[0])17971798 for bp in bps:1799 funcs = chain(funcs, self.url_default_functions[bp])18001801 for func in funcs:1802 func(endpoint, values)18031804 def handle_url_build_error(
32 unmodified lines
18371838 funcs: t.Iterable[URLValuePreprocessorCallable] = self.url_value_preprocessors[1839 None1840 ]1834 for bp in self._request_blueprints():1841 for bp in request.blueprints:1842 if bp in self.url_value_preprocessors:1843 funcs = chain(funcs, self.url_value_preprocessors[bp])1844 for func in funcs:1845 func(request.endpoint, request.view_args)18461847 funcs: t.Iterable[BeforeRequestCallable] = self.before_request_funcs[None]1841 for bp in self._request_blueprints():1848 for bp in request.blueprints:1849 if bp in self.before_request_funcs:1850 funcs = chain(funcs, self.before_request_funcs[bp])1851 for func in funcs:1852 rv = self.ensure_sync(func)()
16 unmodified lines
1869 instance of :attr:`response_class`.1870 """1871 ctx = _request_ctx_stack.top1872 funcs: t.Iterable[AfterRequestCallable] = ctx._after_request_functions1866 for bp in self._request_blueprints():1873 for bp in request.blueprints:1874 if bp in self.after_request_funcs:1875 funcs = chain(funcs, reversed(self.after_request_funcs[bp]))1876 if None in self.after_request_funcs:1877 funcs = chain(funcs, reversed(self.after_request_funcs[None]))
30 unmodified lines
1908 exc = sys.exc_info()[1]1909 funcs: t.Iterable[TeardownCallable] = reversed(1910 self.teardown_request_funcs[None]1911 )1905 for bp in self._request_blueprints():1912 for bp in request.blueprints:1913 if bp in self.teardown_request_funcs:1914 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1915 for func in funcs:1916 self.ensure_sync(func)(exc)
163 unmodified lines
2080 WSGI application. This calls :meth:`wsgi_app`, which can be2081 wrapped to apply middleware.2082 """2083 return self.wsgi_app(environ, start_response)20772078 def _request_blueprints(self) -> t.Iterable[str]:2079 if _request_ctx_stack.top.request.blueprint is None:2080 return []2081 else:2082 return reversed(_request_ctx_stack.top.request.blueprint.split("."))
modified:src/flask/blueprints.py+19 added-19 removed
96 unmodified lines
97 if "defaults" in options:98 defaults = dict(defaults, **options.pop("defaults"))99 self.app.add_url_rule(100 rule,101 f"{self.name_prefix}{self.blueprint.name}.{endpoint}",101 f"{self.name_prefix}.{self.blueprint.name}.{endpoint}".lstrip("."),102 view_func,103 defaults=defaults,104 **options,105 )
159 unmodified lines
265 :param app: The application this blueprint is being registered266 with.267 :param options: Keyword arguments forwarded from268 :meth:`~Flask.register_blueprint`.269 :param first_registration: Whether this is the first time this270 blueprint has been registered on the application.269 """272 first_registration = False270 first_registration = True271274 if self.name in app.blueprints:275 assert app.blueprints[self.name] is self, (276 "A name collision occurred between blueprints"277 f" {self!r} and {app.blueprints[self.name]!r}."278 f" Both share the same name {self.name!r}."279 f" Blueprints that are created on the fly need unique"280 f" names."272 for blueprint in app.blueprints.values():273 if blueprint is self:274 first_registration = False275276 name_prefix = options.get("name_prefix", "")277 name = f"{name_prefix}.{self.name}".lstrip(".")278279 if name in app.blueprints and app.blueprints[name] is not self:280 raise ValueError(281 f"Blueprint name '{self.name}' "282 f"is already registered by {app.blueprints[self.name]}. "283 "Blueprints must have unique names."284 )282 else:283 app.blueprints[self.name] = self284 first_registration = True285286 app.blueprints[name] = self287 self._got_registered_once = True288 state = self.make_setup_state(app, options, first_registration)289290 if self.has_static_folder:
7 unmodified lines
298 if first_registration:299300 def extend(bp_dict, parent_dict):301 for key, values in bp_dict.items():301 key = self.name if key is None else f"{self.name}.{key}"302302 key = name if key is None else f"{name}.{key}"303 parent_dict[key].extend(values)304305 for key, value in self.error_handler_spec.items():306 key = self.name if key is None else f"{self.name}.{key}"306 key = name if key is None else f"{name}.{key}"307 value = defaultdict(308 dict,309 {310 code: {
25 unmodified lines
336 if self.cli.commands:337 if cli_resolved_group is None:338 app.cli.commands.update(self.cli.commands)339 elif cli_resolved_group is _sentinel:340 self.cli.name = self.name340 self.cli.name = name341 app.cli.add_command(self.cli)342 else:343 self.cli.name = cli_resolved_group344 app.cli.add_command(self.cli)
13 unmodified lines
358 bp_options["url_prefix"] = bp_url_prefix359 elif state.url_prefix is not None:360 bp_options["url_prefix"] = state.url_prefix361362 bp_options["name_prefix"] = options.get("name_prefix", "") + self.name + "."362 bp_options["name_prefix"] = name363 blueprint.register(app, bp_options)364365 def add_url_rule(366 self,
203 unmodified lines
modified:src/flask/wrappers.py+16 added
1import typing as t23from werkzeug.exceptions import BadRequest4from werkzeug.utils import cached_property5from werkzeug.wrappers import Request as RequestBase6from werkzeug.wrappers import Response as ResponseBase78from . import json
68 unmodified lines
77 return self.url_rule.endpoint.rsplit(".", 1)[0]78 else:79 return None8081 @cached_property82 def blueprints(self) -> t.List[str]:83 """The names of the current blueprint upwards through parent84 blueprints.85 """86 if self.blueprint is None:87 return []8889 bps: t.List[str] = [self.blueprint]9091 while "." in bps[-1]:92 bps.append(bps[-1].rpartition(".")[0])9394 return bps9596 def _load_form_data(self) -> None:97 RequestBase._load_form_data(self)9899 # In debug mode we're replacing the files multidict with an ad-hoc
52 unmodified lines