use similar code for all callback-applying methods
Before adoption: this commit came in with the history the project adopted, so no landing records it.
avoid building nested chain iterables avoid triggering defaultdict when looking up registries apply functions as they are looked up
authored by David Lord · committed by David Lord · parent 166a2a6 · Browse files · 1 file·+52 added−51 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+52 added−51 removed
- other:+52 added−51 removed
Provenance
- Commit
3f6cdbd- Tree
5274bfb- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
166a2a6
1 file changed+52 added−51 removed
modified:src/flask/app.py+52 added-51 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[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 reversed(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(1810- self.url_default_functions[bp] for bp in reversed(bps)1805+ names = chain(1806+ names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))1807 )1812- funcs = chain(funcs, bp_funcs)1808 1814- for func in funcs:1815- 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 1851- funcs: t.Iterable[URLValuePreprocessorCallable] = []1852- for name in chain([None], reversed(request.blueprints)):1849+ for name in names:1850 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)1851+ for url_func in self.url_value_preprocessors[name]:1852+ url_func(request.endpoint, request.view_args)1853 1858- funcs: t.Iterable[BeforeRequestCallable] = []1859- for name in chain([None], reversed(request.blueprints)):1854+ for name in names:1855 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 rv1856+ 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 name in chain(request.blueprints, [None]):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:1886- funcs = chain(funcs, reversed(self.after_request_funcs[name]))1887- for handler in funcs:1888- response = self.ensure_sync(handler)(response)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]1918- funcs: t.Iterable[TeardownCallable] = []1919- for name in chain(request.blueprints, [None]):1917+1918+ for name in chain(request.blueprints, (None,)):1919 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)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 lines