Merge pull request #4230 from matipau/blueprint-fix
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fix callback order for nested blueprints
authored by David Lord · committed by GitHub · parents 4346498, 3f6cdbd · Browse files · 3 files·+140 added−60 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+140 added−60 removed
- tests:+80 added−0 removed
- other:+60 added−60 removed
Provenance
- Commit
6d637f0- Tree
5274bfb- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
4346498- Parent 2
3f6cdbd
3 files changed+140 added−60 removed
modified:src/flask/app.py+57 added-60 removed
56 unmodified lines57 from .signals import request_started58 from .signals import request_tearing_down59 from .templating import DispatchingJinjaLoader60 from .templating import Environment61-from .typing import AfterRequestCallable61 from .typing import BeforeFirstRequestCallable63-from .typing import BeforeRequestCallable62 from .typing import ResponseReturnValue63 from .typing import TeardownCallable66-from .typing import TemplateContextProcessorCallable64 from .typing import TemplateFilterCallable65 from .typing import TemplateGlobalCallable66 from .typing import TemplateTestCallable70-from .typing import URLDefaultCallable71-from .typing import URLValuePreprocessorCallable67 from .wrappers import Request68 from .wrappers import Response69 70 if t.TYPE_CHECKING:668 unmodified lines739 740 :param context: the context as a dictionary that is updated in place741 to add extra variables.742 """748- funcs: t.Iterable[749- TemplateContextProcessorCallable750- ] = self.template_context_processors[None]751- reqctx = _request_ctx_stack.top752- if reqctx is not None:753- for bp in request.blueprints:754- if bp in self.template_context_processors:755- funcs = chain(funcs, self.template_context_processors[bp])743+ names: t.Iterable[t.Optional[str]] = (None,)744+745+ # A template may be rendered outside a request context.746+ if request:747+ names = chain(names, reversed(request.blueprints))748+749+ # The values passed to render_template take precedence. Keep a750+ # copy to re-apply after all context functions.751 orig_ctx = context.copy()757- for func in funcs:758- context.update(func())759- # make sure the original values win. This makes it possible to760- # easier add new variables in context processors without breaking761- # existing views.752+753+ for name in names:754+ if name in self.template_context_processors:755+ for func in self.template_context_processors[name]:756+ context.update(func())757+758 context.update(orig_ctx)759 760 def make_shell_context(self) -> dict:761 """Returns the shell context for an interactive shell for this511 unmodified lines1273 blueprint handler for an exception class, app handler for an exception1274 class, or ``None`` if a suitable handler is not found.1275 """1276 exc_class, code = self._get_exc_class_and_code(type(e))1277+ names = (*request.blueprints, None)1278 1282- for c in [code, None] if code is not None else [None]:1283- for name in chain(request.blueprints, [None]):1279+ for c in (code, None) if code is not None else (None,):1280+ for name in names:1281 handler_map = self.error_handler_spec[name][c]1282 1283 if not handler_map:1284 continue511 unmodified lines1796 automatically called on URL building.1797 1798 .. versionadded:: 0.71799 """1803- funcs: t.Iterable[URLDefaultCallable] = self.url_default_functions[None]1800+ names: t.Iterable[t.Optional[str]] = (None,)1801 1802+ # url_for may be called outside a request context, parse the1803+ # passed endpoint instead of using request.blueprints.1804 if "." in endpoint:1806- # This is called by url_for, which can be called outside a1807- # request, can't use request.blueprints.1808- bps = _split_blueprint_path(endpoint.rpartition(".")[0])1809- bp_funcs = chain.from_iterable(self.url_default_functions[bp] for bp in bps)1810- funcs = chain(funcs, bp_funcs)1805+ names = chain(1806+ names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))1807+ )1808 1812- for func in funcs:1813- func(endpoint, values)1809+ for name in names:1810+ if name in self.url_default_functions:1811+ for func in self.url_default_functions[name]:1812+ func(endpoint, values)1813 1814 def handle_url_build_error(1815 self, error: Exception, endpoint: str, values: dict1816 ) -> str:26 unmodified lines1843 If any :meth:`before_request` handler returns a non-None value, the1844 value is handled as if it was the return value from the view, and1845 further request handling is stopped.1846 """1847+ names = (None, *reversed(request.blueprints))1848 1849- funcs: t.Iterable[URLValuePreprocessorCallable] = self.url_value_preprocessors[1850- None1851- ]1852- for bp in request.blueprints:1853- if bp in self.url_value_preprocessors:1854- funcs = chain(funcs, self.url_value_preprocessors[bp])1855- for func in funcs:1856- func(request.endpoint, request.view_args)1849+ for name in names:1850+ if name in self.url_value_preprocessors:1851+ for url_func in self.url_value_preprocessors[name]:1852+ url_func(request.endpoint, request.view_args)1853 1858- funcs: t.Iterable[BeforeRequestCallable] = self.before_request_funcs[None]1859- for bp in request.blueprints:1860- if bp in self.before_request_funcs:1861- funcs = chain(funcs, self.before_request_funcs[bp])1862- for func in funcs:1863- rv = self.ensure_sync(func)()1864- if rv is not None:1865- return rv1854+ for name in names:1855+ if name in self.before_request_funcs:1856+ for before_func in self.before_request_funcs[name]:1857+ rv = self.ensure_sync(before_func)()1858 1859+ if rv is not None:1860+ return rv1861+1862 return None1863 1864 def process_response(self, response: Response) -> Response:1865 """Can be overridden in order to modify the response object8 unmodified lines1874 :return: a new response object or the same, has to be an1875 instance of :attr:`response_class`.1876 """1877 ctx = _request_ctx_stack.top1883- funcs: t.Iterable[AfterRequestCallable] = ctx._after_request_functions1884- for bp in request.blueprints:1885- if bp in self.after_request_funcs:1886- funcs = chain(funcs, reversed(self.after_request_funcs[bp]))1887- if None in self.after_request_funcs:1888- funcs = chain(funcs, reversed(self.after_request_funcs[None]))1889- for handler in funcs:1890- response = self.ensure_sync(handler)(response)1878+1879+ for func in ctx._after_request_functions:1880+ response = self.ensure_sync(func)(response)1881+1882+ for name in chain(request.blueprints, (None,)):1883+ if name in self.after_request_funcs:1884+ for func in reversed(self.after_request_funcs[name]):1885+ response = self.ensure_sync(func)(response)1886+1887 if not self.session_interface.is_null_session(ctx.session):1888 self.session_interface.save_session(self, ctx.session, response)1889+1890 return response1891 1892 def do_teardown_request(1893 self, exc: t.Optional[BaseException] = _sentinel # type: ignore19 unmodified lines1913 Added the ``exc`` argument.1914 """1915 if exc is _sentinel:1916 exc = sys.exc_info()[1]1920- funcs: t.Iterable[TeardownCallable] = reversed(1921- self.teardown_request_funcs[None]1922- )1923- for bp in request.blueprints:1924- if bp in self.teardown_request_funcs:1925- funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1926- for func in funcs:1927- self.ensure_sync(func)(exc)1917+1918+ for name in chain(request.blueprints, (None,)):1919+ if name in self.teardown_request_funcs:1920+ for func in reversed(self.teardown_request_funcs[name]):1921+ self.ensure_sync(func)(exc)1922+1923 request_tearing_down.send(self, exc=exc)1924 1925 def do_teardown_appcontext(1926 self, exc: t.Optional[BaseException] = _sentinel # type: ignore13 unmodified lines1940 .. versionadded:: 0.91941 """1942 if exc is _sentinel:1943 exc = sys.exc_info()[1]1944+1945 for func in reversed(self.teardown_appcontext_funcs):1946 self.ensure_sync(func)(exc)1947+1948 appcontext_tearing_down.send(self, exc=exc)1949 1950 def app_context(self) -> AppContext:1951 """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``140 unmodified linesmodified:tests/test_blueprints.py+80 added
835 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_callback_order(app, client):841+ parent = flask.Blueprint("parent", __name__)842+ child = flask.Blueprint("child", __name__)843+844+ @app.before_request845+ def app_before1():846+ flask.g.setdefault("seen", []).append("app_1")847+848+ @app.teardown_request849+ def app_teardown1(e=None):850+ assert flask.g.seen.pop() == "app_1"851+852+ @app.before_request853+ def app_before2():854+ flask.g.setdefault("seen", []).append("app_2")855+856+ @app.teardown_request857+ def app_teardown2(e=None):858+ assert flask.g.seen.pop() == "app_2"859+860+ @app.context_processor861+ def app_ctx():862+ return dict(key="app")863+864+ @parent.before_request865+ def parent_before1():866+ flask.g.setdefault("seen", []).append("parent_1")867+868+ @parent.teardown_request869+ def parent_teardown1(e=None):870+ assert flask.g.seen.pop() == "parent_1"871+872+ @parent.before_request873+ def parent_before2():874+ flask.g.setdefault("seen", []).append("parent_2")875+876+ @parent.teardown_request877+ def parent_teardown2(e=None):878+ assert flask.g.seen.pop() == "parent_2"879+880+ @parent.context_processor881+ def parent_ctx():882+ return dict(key="parent")883+884+ @child.before_request885+ def child_before1():886+ flask.g.setdefault("seen", []).append("child_1")887+888+ @child.teardown_request889+ def child_teardown1(e=None):890+ assert flask.g.seen.pop() == "child_1"891+892+ @child.before_request893+ def child_before2():894+ flask.g.setdefault("seen", []).append("child_2")895+896+ @child.teardown_request897+ def child_teardown2(e=None):898+ assert flask.g.seen.pop() == "child_2"899+900+ @child.context_processor901+ def child_ctx():902+ return dict(key="child")903+904+ @child.route("/a")905+ def a():906+ return ", ".join(flask.g.seen)907+908+ @child.route("/b")909+ def b():910+ return flask.render_template_string("{{ key }}")911+912+ parent.register_blueprint(child)913+ app.register_blueprint(parent)914+ assert (915+ client.get("/a").data == b"app_1, app_2, parent_1, parent_2, child_1, child_2"916+ )917+ assert client.get("/b").data == b"child"918+919+920 @pytest.mark.parametrize(921 "parent_init, child_init, parent_registration, child_registration",922 [923 ("/parent", "/child", None, None),80 unmodified linesmodified:CHANGES.rst+3 added
19 unmodified lines20 - Correctly handle raising deferred errors in CLI lazy loading.21 :issue:`4096`22 - The CLI loader handles ``**kwargs`` in a ``create_app`` function.23 :issue:`4170`24+- Fix the order of ``before_request`` and other callbacks that trigger25+ before the view returns. They are called from the app down to the26+ closest nested blueprint. :issue:`4229`27 28 29 Version 2.0.130 -------------1154 unmodified lines