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
Provenance
- Commit
141fde1- Tree
6f440fd- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
pgjones <philip.graham.jones@googlemail.com>- Parent
99afbb2
3 files changed+50 added−33 removed
modified:src/flask/app.py+15 added-14 removed
745 unmodified lines746 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 lines1266 """1267 exc_class, code = self._get_exc_class_and_code(type(e))1268 1269 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]1272 1273 if not handler_map:1274 continue512 unmodified lines1787 1788 .. versionadded:: 0.71789 """1790 funcs: t.Iterable[URLDefaultCallable] = self.url_default_functions[None]1791+1792 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]]1794+1795+ while "." in bps[-1]:1796+ bps.append(bps[-1].rpartition(".")[0])1797+1798+ for bp in bps:1799+ funcs = chain(funcs, self.url_default_functions[bp])1800+1801 for func in funcs:1802 func(endpoint, values)1803 1804 def handle_url_build_error(32 unmodified lines1837 1838 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)1846 1847 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 lines1869 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 lines1908 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 lines2080 WSGI application. This calls :meth:`wsgi_app`, which can be2081 wrapped to apply middleware.2082 """2083 return self.wsgi_app(environ, start_response)2077-2078- 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 lines97 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 lines265 :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 = True271 274- 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 = False275+276+ name_prefix = options.get("name_prefix", "")277+ name = f"{name_prefix}.{self.name}".lstrip(".")278+279+ 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 = True285 286+ app.blueprints[name] = self287 self._got_registered_once = True288 state = self.make_setup_state(app, options, first_registration)289 290 if self.has_static_folder:7 unmodified lines298 if first_registration:299 300 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}"302-302+ key = name if key is None else f"{name}.{key}"303 parent_dict[key].extend(values)304 305 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 lines336 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 lines358 bp_options["url_prefix"] = bp_url_prefix359 elif state.url_prefix is not None:360 bp_options["url_prefix"] = state.url_prefix361 362- bp_options["name_prefix"] = options.get("name_prefix", "") + self.name + "."362+ bp_options["name_prefix"] = name363 blueprint.register(app, bp_options)364 365 def add_url_rule(366 self,203 unmodified linesmodified:src/flask/wrappers.py+16 added
1 import typing as t2 3 from werkzeug.exceptions import BadRequest4+from werkzeug.utils import cached_property5 from werkzeug.wrappers import Request as RequestBase6 from werkzeug.wrappers import Response as ResponseBase7 8 from . import json68 unmodified lines77 return self.url_rule.endpoint.rsplit(".", 1)[0]78 else:79 return None80 81+ @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 []88+89+ bps: t.List[str] = [self.blueprint]90+91+ while "." in bps[-1]:92+ bps.append(bps[-1].rpartition(".")[0])93+94+ return bps95+96 def _load_form_data(self) -> None:97 RequestBase._load_form_data(self)98 99 # In debug mode we're replacing the files multidict with an ad-hoc52 unmodified lines