Skip to content
Myr

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

6 files+203 added−81 removed

modified:src/flask/app.py+20 added-14 removed
34 unmodified lines
35from .globals import _request_ctx_stack36from .globals import g37from .globals import request38from .globals import session39from .helpers import _split_blueprint_path40from .helpers import get_debug_flag41from .helpers import get_env42from .helpers import get_flashed_messages43from .helpers import get_load_dotenv
703 unmodified lines
747 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 lines
1018 :param options: Additional keyword arguments are passed to1019 :class:`~flask.blueprints.BlueprintSetupState`. They can be1020 accessed in :meth:`~flask.Blueprint.record` callbacks.10211022 .. 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``.10271028 .. versionadded:: 0.71029 """1030 blueprint.register(self, options)1031
241 unmodified lines
1273 """1274 exc_class, code = self._get_exc_class_and_code(type(e))12751276 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]12791280 if not handler_map:1281 continue
512 unmodified lines
17941795 .. versionadded:: 0.71796 """1797 funcs: t.Iterable[URLDefaultCallable] = self.url_default_functions[None]17981799 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)18051806 for func in funcs:1807 func(endpoint, values)18081809 def handle_url_build_error(
32 unmodified lines
18421843 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)18511852 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 lines
1874 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 lines
1913 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 lines
2085 WSGI application. This calls :meth:`wsgi_app`, which can be2086 wrapped to apply middleware.2087 """2088 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+57 added-21 removed
65 unmodified lines
66 #: The prefix that should be used for all URLs defined on the67 #: blueprint.68 self.url_prefix = url_prefix6970 self.name = self.options.get("name", blueprint.name)71 self.name_prefix = self.options.get("name_prefix", "")7273 #: A dictionary with URL defaults that is added to each and every74 #: URL that was defined with the blueprint.
21 unmodified lines
96 endpoint = _endpoint_from_view_func(view_func) # type: ignore97 defaults = self.url_defaults98 if "defaults" in options:99 defaults = dict(defaults, **options.pop("defaults"))100101 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 lines
253 """Register a :class:`~flask.Blueprint` on this blueprint. Keyword254 arguments passed to this method will override the defaults set255 on the blueprint.256257 .. 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``.262263 .. versionadded:: 2.0264 """265 if blueprint is self:266 raise ValueError("Cannot register a blueprint on itself")267 self._blueprints.append((blueprint, options))268269 def register(self, app: "Flask", options: dict) -> None:270 """Called by :meth:`Flask.register_blueprint` to register all
4 unmodified lines
275 :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.279280 .. 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.284285 .. 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``.290291 .. 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(".")299274 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 ""302303 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 warnings311312 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 )319320 app.blueprints[name] = self321 self._got_registered_once = True322 state = self.make_setup_state(app, options, first_registration)323324 if self.has_static_folder:
7 unmodified lines
332 if first_registration:333334 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}"302336 key = name if key is None else f"{name}.{key}"337 parent_dict[key].extend(values)338339 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 lines
370 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 lines
387 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_prefix395360 bp_options["name_prefix"] = options.get("name_prefix", "") + self.name + "."396 bp_options["name_prefix"] = name397 blueprint.register(app, bp_options)398399 def add_url_rule(400 self,
203 unmodified lines
modified:src/flask/helpers.py+11 added
4 unmodified lines
5import typing as t6import warnings7from datetime import datetime8from datetime import timedelta9from functools import lru_cache10from functools import update_wrapper11from threading import RLock1213import werkzeug.utils
807 unmodified lines
821 else:822 return True823824 return False825826827@lru_cache(maxsize=None)828def _split_blueprint_path(name: str) -> t.List[str]:829 out: t.List[str] = [name]830831 if "." in name:832 out.extend(_split_blueprint_path(name.rpartition(".")[0]))833834 return out
modified:src/flask/wrappers.py+43 added-11 removed
4 unmodified lines
5from werkzeug.wrappers import Response as ResponseBase67from . import json8from .globals import current_app9from .helpers import _split_blueprint_path1011if t.TYPE_CHECKING:12 import typing_extensions as te13 from werkzeug.routing import Rule
45 unmodified lines
59 return None6061 @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.6465 This will be ``None`` if matching failed or has not been66 performed yet.6768 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 None7374 return None7576 @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.7980 This will be ``None`` if the endpoint is not part of a81 blueprint, or if URL matching failed or has not been performed82 yet.8384 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.endpoint8990 if endpoint is not None and "." in endpoint:91 return endpoint.rpartition(".")[0]9293 return None9495 @property96 def blueprints(self) -> t.List[str]:97 """The registered names of the current blueprint upwards through98 parent blueprints.99100 This will be an empty list if there is no current blueprint, or101 if URL matching failed.102103 .. versionadded:: 2.0.1104 """105 name = self.blueprint106107 if name is None:108 return []109110 return _split_blueprint_path(name)111112 def _load_form_data(self) -> None:113 RequestBase._load_form_data(self)114115 # In debug mode we're replacing the files multidict with an ad-hoc
52 unmodified lines
modified:tests/test_blueprints.py+64 added-35 removed
138 unmodified lines
139 def bar(bar):140 return str(bar)141142 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})144145 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 lines
836 assert client.get("/parent/child/no").data == b"Parent no"837 assert client.get("/parent/child/grandchild/no").data == b"Grandchild no"838839840def 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)849def 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)859846 @parent.route("/")847 def parent_index():848 return "Parent"849860 @child.route("/")851 def child_index():852 return "Child"861 def index():862 return "index"863854 @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)866858 @apple.route("/")859 def apple_index():860 return "Apple"867 response = client.get("/parent/child/")868 assert response.status_code == 200869862 child.register_blueprint(grandchild)863 child.register_blueprint(apple, url_prefix="/orange") # test overwrite864 parent.register_blueprint(child)865 app.register_blueprint(parent)870867 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"871def test_unique_blueprint_names(app, client) -> None:872 bp = flask.Blueprint("bp", __name__)873 bp2 = flask.Blueprint("bp", __name__)874875 app.register_blueprint(bp)876873def 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, warning879877 @child.route("/child-endpoint")878 def child_index():879 return "Child"880 app.register_blueprint(bp, name="again") # same bp, different name, ok881881 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, error884884 assert client.get("/parent/child-endpoint").data == b"Child"885 app.register_blueprint(bp2, name="alt") # different bp, different name, ok886887888def test_self_registration(app, client) -> None:889 bp = flask.Blueprint("bp", __name__)890 with pytest.raises(ValueError):891 bp.register_blueprint(bp)892893894def test_blueprint_renaming(app, client) -> None:895 bp = flask.Blueprint("bp", __name__)896 bp2 = flask.Blueprint("bp2", __name__)897898 @bp.get("/")899 def index():900 return flask.request.endpoint901902 @bp2.get("/")903 def index2():904 return flask.request.endpoint905906 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")909910 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 lines
26- 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`383940Version 2.0.041-------------
1116 unmodified lines