Merge pull request #4074 from pgjones/bp
Before adoption: this commit came in with the history the project adopted, so no landing records it.
blueprints are registered with nested names, can change registered name
authored by David Lord · committed by GitHub · parents a541c2a, 3257b75 · Browse files · 6 files·+203 added−81 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+203 added−81 removed
- tests:+64 added−35 removed
- other:+139 added−46 removed
Provenance
- Commit
255461d- Tree
0a32707- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
a541c2a- Parent 2
3257b75
6 files changed+203 added−81 removed
modified:src/flask/app.py+20 added-14 removed
34 unmodified lines35 from .globals import _request_ctx_stack36 from .globals import g37 from .globals import request38 from .globals import session39+from .helpers import _split_blueprint_path40 from .helpers import get_debug_flag41 from .helpers import get_env42 from .helpers import get_flashed_messages43 from .helpers import get_load_dotenv703 unmodified lines747 TemplateContextProcessorCallable748 ] = self.template_context_processors[None]749 reqctx = _request_ctx_stack.top750 if reqctx is not None:750- for bp in self._request_blueprints():751+ for bp in request.blueprints:752 if bp in self.template_context_processors:753 funcs = chain(funcs, self.template_context_processors[bp])754 orig_ctx = context.copy()755 for func in funcs:262 unmodified lines1018 :param options: Additional keyword arguments are passed to1019 :class:`~flask.blueprints.BlueprintSetupState`. They can be1020 accessed in :meth:`~flask.Blueprint.record` callbacks.1021 1022+ .. versionchanged:: 2.0.11023+ The ``name`` option can be used to change the (pre-dotted)1024+ name the blueprint is registered with. This allows the same1025+ blueprint to be registered multiple times with unique names1026+ for ``url_for``.1027+1028 .. versionadded:: 0.71029 """1030 blueprint.register(self, options)1031 241 unmodified lines1273 """1274 exc_class, code = self._get_exc_class_and_code(type(e))1275 1276 for c in [code, None]:1270- for name in chain(self._request_blueprints(), [None]):1277+ for name in chain(request.blueprints, [None]):1278 handler_map = self.error_handler_spec[name][c]1279 1280 if not handler_map:1281 continue512 unmodified lines1794 1795 .. versionadded:: 0.71796 """1797 funcs: t.Iterable[URLDefaultCallable] = self.url_default_functions[None]1798+1799 if "." in endpoint:1792- bp = endpoint.rsplit(".", 1)[0]1793- funcs = chain(funcs, self.url_default_functions[bp])1800+ # This is called by url_for, which can be called outside a1801+ # request, can't use request.blueprints.1802+ bps = _split_blueprint_path(endpoint.rpartition(".")[0])1803+ bp_funcs = chain.from_iterable(self.url_default_functions[bp] for bp in bps)1804+ funcs = chain(funcs, bp_funcs)1805+1806 for func in funcs:1807 func(endpoint, values)1808 1809 def handle_url_build_error(32 unmodified lines1842 1843 funcs: t.Iterable[URLValuePreprocessorCallable] = self.url_value_preprocessors[1844 None1845 ]1834- for bp in self._request_blueprints():1846+ for bp in request.blueprints:1847 if bp in self.url_value_preprocessors:1848 funcs = chain(funcs, self.url_value_preprocessors[bp])1849 for func in funcs:1850 func(request.endpoint, request.view_args)1851 1852 funcs: t.Iterable[BeforeRequestCallable] = self.before_request_funcs[None]1841- for bp in self._request_blueprints():1853+ for bp in request.blueprints:1854 if bp in self.before_request_funcs:1855 funcs = chain(funcs, self.before_request_funcs[bp])1856 for func in funcs:1857 rv = self.ensure_sync(func)()16 unmodified lines1874 instance of :attr:`response_class`.1875 """1876 ctx = _request_ctx_stack.top1877 funcs: t.Iterable[AfterRequestCallable] = ctx._after_request_functions1866- for bp in self._request_blueprints():1878+ for bp in request.blueprints:1879 if bp in self.after_request_funcs:1880 funcs = chain(funcs, reversed(self.after_request_funcs[bp]))1881 if None in self.after_request_funcs:1882 funcs = chain(funcs, reversed(self.after_request_funcs[None]))30 unmodified lines1913 exc = sys.exc_info()[1]1914 funcs: t.Iterable[TeardownCallable] = reversed(1915 self.teardown_request_funcs[None]1916 )1905- for bp in self._request_blueprints():1917+ for bp in request.blueprints:1918 if bp in self.teardown_request_funcs:1919 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1920 for func in funcs:1921 self.ensure_sync(func)(exc)163 unmodified lines2085 WSGI application. This calls :meth:`wsgi_app`, which can be2086 wrapped to apply middleware.2087 """2088 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+57 added-21 removed
65 unmodified lines66 #: The prefix that should be used for all URLs defined on the67 #: blueprint.68 self.url_prefix = url_prefix69 70+ self.name = self.options.get("name", blueprint.name)71 self.name_prefix = self.options.get("name_prefix", "")72 73 #: A dictionary with URL defaults that is added to each and every74 #: URL that was defined with the blueprint.21 unmodified lines96 endpoint = _endpoint_from_view_func(view_func) # type: ignore97 defaults = self.url_defaults98 if "defaults" in options:99 defaults = dict(defaults, **options.pop("defaults"))100+101 self.app.add_url_rule(102 rule,101- f"{self.name_prefix}{self.blueprint.name}.{endpoint}",103+ f"{self.name_prefix}.{self.name}.{endpoint}".lstrip("."),104 view_func,105 defaults=defaults,106 **options,107 )145 unmodified lines253 """Register a :class:`~flask.Blueprint` on this blueprint. Keyword254 arguments passed to this method will override the defaults set255 on the blueprint.256 257+ .. versionchanged:: 2.0.1258+ The ``name`` option can be used to change the (pre-dotted)259+ name the blueprint is registered with. This allows the same260+ blueprint to be registered multiple times with unique names261+ for ``url_for``.262+263 .. versionadded:: 2.0264 """265+ if blueprint is self:266+ raise ValueError("Cannot register a blueprint on itself")267 self._blueprints.append((blueprint, options))268 269 def register(self, app: "Flask", options: dict) -> None:270 """Called by :meth:`Flask.register_blueprint` to register all4 unmodified lines275 :param app: The application this blueprint is being registered276 with.277 :param options: Keyword arguments forwarded from278 :meth:`~Flask.register_blueprint`.269- :param first_registration: Whether this is the first time this270- blueprint has been registered on the application.279+280+ .. versionchanged:: 2.0.1281+ Nested blueprints are registered with their dotted name.282+ This allows different blueprints with the same name to be283+ nested at different locations.284+285+ .. versionchanged:: 2.0.1286+ The ``name`` option can be used to change the (pre-dotted)287+ name the blueprint is registered with. This allows the same288+ blueprint to be registered multiple times with unique names289+ for ``url_for``.290+291+ .. versionchanged:: 2.0.1292+ Registering the same blueprint with the same name multiple293+ times is deprecated and will become an error in Flask 2.1.294 """272- first_registration = False295+ first_registration = not any(bp is self for bp in app.blueprints.values())296+ name_prefix = options.get("name_prefix", "")297+ self_name = options.get("name", self.name)298+ name = f"{name_prefix}.{self_name}".lstrip(".")299 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."281- )282- else:283- app.blueprints[self.name] = self284- first_registration = True300+ if name in app.blueprints:301+ existing_at = f" '{name}'" if self_name != name else ""302 303+ if app.blueprints[name] is not self:304+ raise ValueError(305+ f"The name '{self_name}' is already registered for"306+ f" a different blueprint{existing_at}. Use 'name='"307+ " to provide a unique name."308+ )309+ else:310+ import warnings311+312+ warnings.warn(313+ f"The name '{self_name}' is already registered for"314+ f" this blueprint{existing_at}. Use 'name=' to"315+ " provide a unique name. This will become an error"316+ " in Flask 2.1.",317+ stacklevel=4,318+ )319+320+ app.blueprints[name] = self321 self._got_registered_once = True322 state = self.make_setup_state(app, options, first_registration)323 324 if self.has_static_folder:7 unmodified lines332 if first_registration:333 334 def extend(bp_dict, parent_dict):335 for key, values in bp_dict.items():301- key = self.name if key is None else f"{self.name}.{key}"302-336+ key = name if key is None else f"{name}.{key}"337 parent_dict[key].extend(values)338 339 for key, value in self.error_handler_spec.items():306- key = self.name if key is None else f"{self.name}.{key}"340+ key = name if key is None else f"{name}.{key}"341 value = defaultdict(342 dict,343 {344 code: {25 unmodified lines370 if self.cli.commands:371 if cli_resolved_group is None:372 app.cli.commands.update(self.cli.commands)373 elif cli_resolved_group is _sentinel:340- self.cli.name = self.name374+ self.cli.name = name375 app.cli.add_command(self.cli)376 else:377 self.cli.name = cli_resolved_group378 app.cli.add_command(self.cli)8 unmodified lines387 if state.url_prefix is not None and bp_url_prefix is not None:388 bp_options["url_prefix"] = (389 state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/")390 )357- else:391+ elif bp_url_prefix is not None:392+ bp_options["url_prefix"] = bp_url_prefix393+ elif state.url_prefix is not None:394 bp_options["url_prefix"] = state.url_prefix395 360- bp_options["name_prefix"] = options.get("name_prefix", "") + self.name + "."396+ bp_options["name_prefix"] = name397 blueprint.register(app, bp_options)398 399 def add_url_rule(400 self,203 unmodified linesmodified:src/flask/helpers.py+11 added
4 unmodified lines5 import typing as t6 import warnings7 from datetime import datetime8 from datetime import timedelta9+from functools import lru_cache10 from functools import update_wrapper11 from threading import RLock12 13 import werkzeug.utils807 unmodified lines821 else:822 return True823 824 return False825+826+827+@lru_cache(maxsize=None)828+def _split_blueprint_path(name: str) -> t.List[str]:829+ out: t.List[str] = [name]830+831+ if "." in name:832+ out.extend(_split_blueprint_path(name.rpartition(".")[0]))833+834+ return outmodified:src/flask/wrappers.py+43 added-11 removed
4 unmodified lines5 from werkzeug.wrappers import Response as ResponseBase6 7 from . import json8 from .globals import current_app9+from .helpers import _split_blueprint_path10 11 if t.TYPE_CHECKING:12 import typing_extensions as te13 from werkzeug.routing import Rule45 unmodified lines59 return None60 61 @property62 def endpoint(self) -> t.Optional[str]:62- """The endpoint that matched the request. This in combination with63- :attr:`view_args` can be used to reconstruct the same or a64- modified URL. If an exception happened when matching, this will65- be ``None``.63+ """The endpoint that matched the request URL.64+65+ This will be ``None`` if matching failed or has not been66+ performed yet.67+68+ This in combination with :attr:`view_args` can be used to69+ reconstruct the same URL or a modified URL.70 """71 if self.url_rule is not None:72 return self.url_rule.endpoint69- else:70- return None73 74+ return None75+76 @property77 def blueprint(self) -> t.Optional[str]:74- """The name of the current blueprint"""75- if self.url_rule and "." in self.url_rule.endpoint:76- return self.url_rule.endpoint.rsplit(".", 1)[0]77- else:78- return None78+ """The registered name of the current blueprint.79 80+ This will be ``None`` if the endpoint is not part of a81+ blueprint, or if URL matching failed or has not been performed82+ yet.83+84+ This does not necessarily match the name the blueprint was85+ created with. It may have been nested, or registered with a86+ different name.87+ """88+ endpoint = self.endpoint89+90+ if endpoint is not None and "." in endpoint:91+ return endpoint.rpartition(".")[0]92+93+ return None94+95+ @property96+ def blueprints(self) -> t.List[str]:97+ """The registered names of the current blueprint upwards through98+ parent blueprints.99+100+ This will be an empty list if there is no current blueprint, or101+ if URL matching failed.102+103+ .. versionadded:: 2.0.1104+ """105+ name = self.blueprint106+107+ if name is None:108+ return []109+110+ return _split_blueprint_path(name)111+112 def _load_form_data(self) -> None:113 RequestBase._load_form_data(self)114 115 # In debug mode we're replacing the files multidict with an ad-hoc52 unmodified linesmodified:tests/test_blueprints.py+64 added-35 removed
138 unmodified lines139 def bar(bar):140 return str(bar)141 142 app.register_blueprint(bp, url_prefix="/1", url_defaults={"bar": 23})143- app.register_blueprint(bp, url_prefix="/2", url_defaults={"bar": 19})143+ app.register_blueprint(bp, name="test2", url_prefix="/2", url_defaults={"bar": 19})144 145 assert client.get("/1/foo").data == b"23/42"146 assert client.get("/2/foo").data == b"19/42"147 assert client.get("/1/bar").data == b"23"688 unmodified lines836 assert client.get("/parent/child/no").data == b"Parent no"837 assert client.get("/parent/child/grandchild/no").data == b"Grandchild no"838 839 840-def test_nested_blueprint_url_prefix(app, client):841- parent = flask.Blueprint("parent", __name__, url_prefix="/parent")842- child = flask.Blueprint("child", __name__, url_prefix="/child")843- grandchild = flask.Blueprint("grandchild", __name__, url_prefix="/grandchild")844- apple = flask.Blueprint("apple", __name__, url_prefix="/apple")840+@pytest.mark.parametrize(841+ "parent_init, child_init, parent_registration, child_registration",842+ [843+ ("/parent", "/child", None, None),844+ ("/parent", None, None, "/child"),845+ (None, None, "/parent", "/child"),846+ ("/other", "/something", "/parent", "/child"),847+ ],848+)849+def test_nesting_url_prefixes(850+ parent_init,851+ child_init,852+ parent_registration,853+ child_registration,854+ app,855+ client,856+) -> None:857+ parent = flask.Blueprint("parent", __name__, url_prefix=parent_init)858+ child = flask.Blueprint("child", __name__, url_prefix=child_init)859 846- @parent.route("/")847- def parent_index():848- return "Parent"849-860 @child.route("/")851- def child_index():852- return "Child"861+ def index():862+ return "index"863 854- @grandchild.route("/")855- def grandchild_index():856- return "Grandchild"864+ parent.register_blueprint(child, url_prefix=child_registration)865+ app.register_blueprint(parent, url_prefix=parent_registration)866 858- @apple.route("/")859- def apple_index():860- return "Apple"867+ response = client.get("/parent/child/")868+ assert response.status_code == 200869 862- child.register_blueprint(grandchild)863- child.register_blueprint(apple, url_prefix="/orange") # test overwrite864- parent.register_blueprint(child)865- app.register_blueprint(parent)870 867- assert client.get("/parent/").data == b"Parent"868- assert client.get("/parent/child/").data == b"Child"869- assert client.get("/parent/child/grandchild/").data == b"Grandchild"870- assert client.get("/parent/child/orange/").data == b"Apple"871+def test_unique_blueprint_names(app, client) -> None:872+ bp = flask.Blueprint("bp", __name__)873+ bp2 = flask.Blueprint("bp", __name__)874 875+ app.register_blueprint(bp)876 873-def test_nested_blueprint_url_prefix_only_parent_prefix(app, client):874- parent = flask.Blueprint("parent", __name__)875- child = flask.Blueprint("child", __name__)877+ with pytest.warns(UserWarning):878+ app.register_blueprint(bp) # same bp, same name, warning879 877- @child.route("/child-endpoint")878- def child_index():879- return "Child"880+ app.register_blueprint(bp, name="again") # same bp, different name, ok881 881- parent.register_blueprint(child)882- app.register_blueprint(parent, url_prefix="/parent")882+ with pytest.raises(ValueError):883+ app.register_blueprint(bp2) # different bp, same name, error884 884- assert client.get("/parent/child-endpoint").data == b"Child"885+ app.register_blueprint(bp2, name="alt") # different bp, different name, ok886+887+888+def test_self_registration(app, client) -> None:889+ bp = flask.Blueprint("bp", __name__)890+ with pytest.raises(ValueError):891+ bp.register_blueprint(bp)892+893+894+def test_blueprint_renaming(app, client) -> None:895+ bp = flask.Blueprint("bp", __name__)896+ bp2 = flask.Blueprint("bp2", __name__)897+898+ @bp.get("/")899+ def index():900+ return flask.request.endpoint901+902+ @bp2.get("/")903+ def index2():904+ return flask.request.endpoint905+906+ bp.register_blueprint(bp2, url_prefix="/a", name="sub")907+ app.register_blueprint(bp, url_prefix="/a")908+ app.register_blueprint(bp, url_prefix="/b", name="alt")909+910+ assert client.get("/a/").data == b"bp.index"911+ assert client.get("/b/").data == b"alt.index"912+ assert client.get("/a/a/").data == b"bp.sub.index2"913+ assert client.get("/b/a/").data == b"alt.sub.index2"modified:CHANGES.rst+8 added
25 unmodified lines26 - Re-add deprecated ``Config.from_json``, which was accidentally27 removed early. :issue:`4078`28 - Improve typing for some functions using ``Callable`` in their type29 signatures, focusing on decorator factories. :issue:`4060`30+- Nested blueprints are registered with their dotted name. This allows31+ different blueprints with the same name to be nested at different32+ locations. :issue:`4069`33+- ``register_blueprint`` takes a ``name`` option to change the34+ (pre-dotted) name the blueprint is registered with. This allows the35+ same blueprint to be registered multiple times with unique names for36+ ``url_for``. Registering the same blueprint with the same name37+ multiple times is deprecated. :issue:`1091`38 39 40 Version 2.0.041 -------------1116 unmodified lines