Fix callback order for nested blueprints
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Handlers registered via url_value_preprocessor, before_request, context_processor, and url_defaults are called in downward order: First on the app and last on the current blueprint. Handlers registered via after_request and teardown_request are called in upward order: First on the current blueprint and last on the app.
authored by Matthias Paulsen · committed by David Lord · parent 4346498 · Browse files · 3 files·+105 added−26 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+105 added−26 removed
- tests:+80 added−0 removed
- other:+25 added−26 removed
Provenance
- Commit
166a2a6- Tree
2013b27- Author
Matthias Paulsen <matthias@mp42.de>- Committer
David Lord <davidism@gmail.com>- Parent
4346498
3 files changed+105 added−26 removed
modified:src/flask/app.py+22 added-26 removed
743 unmodified lines744 745 :param context: the context as a dictionary that is updated in place746 to add extra variables.747 """748- funcs: t.Iterable[749- TemplateContextProcessorCallable750- ] = self.template_context_processors[None]748+ funcs: t.Iterable[TemplateContextProcessorCallable] = []749+ if None in self.template_context_processors:750+ funcs = chain(funcs, self.template_context_processors[None])751 reqctx = _request_ctx_stack.top752 if reqctx is not None:753- for bp in request.blueprints:753+ for bp in reversed(request.blueprints):754 if bp in self.template_context_processors:755 funcs = chain(funcs, self.template_context_processors[bp])756 orig_ctx = context.copy()757 for func in funcs:1047 unmodified lines1805 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)1809+ bp_funcs = chain.from_iterable(1810+ self.url_default_functions[bp] for bp in reversed(bps)1811+ )1812 funcs = chain(funcs, bp_funcs)1813 1814 for func in funcs:1815 func(endpoint, values)31 unmodified lines1847 value is handled as if it was the return value from the view, and1848 further request handling is stopped.1849 """1850 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])1851+ funcs: t.Iterable[URLValuePreprocessorCallable] = []1852+ for name in chain([None], reversed(request.blueprints)):1853+ if name in self.url_value_preprocessors:1854+ funcs = chain(funcs, self.url_value_preprocessors[name])1855 for func in funcs:1856 func(request.endpoint, request.view_args)1857 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])1858+ funcs: t.Iterable[BeforeRequestCallable] = []1859+ for name in chain([None], reversed(request.blueprints)):1860+ if name in self.before_request_funcs:1861+ funcs = chain(funcs, self.before_request_funcs[name])1862 for func in funcs:1863 rv = self.ensure_sync(func)()1864 if rv is not None:1865 return rv14 unmodified lines1880 instance of :attr:`response_class`.1881 """1882 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]))1884+ for name in chain(request.blueprints, [None]):1885+ if name in self.after_request_funcs:1886+ funcs = chain(funcs, reversed(self.after_request_funcs[name]))1887 for handler in funcs:1888 response = self.ensure_sync(handler)(response)1889 if not self.session_interface.is_null_session(ctx.session):1890 self.session_interface.save_session(self, ctx.session, response)23 unmodified lines1914 Added the ``exc`` argument.1915 """1916 if exc is _sentinel:1917 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]))1918+ funcs: t.Iterable[TeardownCallable] = []1919+ for name in chain(request.blueprints, [None]):1920+ if name in self.teardown_request_funcs:1921+ funcs = chain(funcs, reversed(self.teardown_request_funcs[name]))1922 for func in funcs:1923 self.ensure_sync(func)(exc)1924 request_tearing_down.send(self, exc=exc)1925 165 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