Merge branch '2.0.x'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parents f4a2c35, 6d637f0 · Browse files · 8 files·+149 added−69 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+149 added−69 removed
- tests:+80 added−0 removed
- other:+69 added−69 removed
Provenance
- Commit
5684f48- Tree
92fc206- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
f4a2c35- Parent 2
6d637f0
8 files changed+149 added−69 removed
modified:artwork/LICENSE.rst+1 added-1 removed
8 unmodified lines9 10 1. Redistributions of source code must retain the above copyright11 notice and this list of conditions.12 13-3. Neither the name of the copyright holder nor the names of its13+2. Neither the name of the copyright holder nor the names of its14 contributors may be used to endorse or promote products derived from15 this software without specific prior written permission.16 17 We would appreciate that you make the image a link to2 unmodified linesmodified:docs/patterns/wtforms.rst+1 added-1 removed
17 unmodified lines18 few little helpers that make working with forms and Flask more19 fun. You can get it from `PyPI20 <https://pypi.org/project/Flask-WTF/>`_.21 22-.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/22+.. _Flask-WTF: https://flask-wtf.readthedocs.io/23 24 The Forms25 ---------26 100 unmodified linesmodified:docs/appcontext.rst+1 added-1 removed
6 unmodified lines7 a request, CLI command, or other activity. Rather than passing the8 application around to each function, the :data:`current_app` and9 :data:`g` proxies are accessed instead.10 11-This is similar to the :doc:`/reqcontext`, which keeps track of11+This is similar to :doc:`/reqcontext`, which keeps track of12 request-level data during a request. A corresponding application context13 is pushed when a request context is pushed.14 15 Purpose of the Context142 unmodified linesmodified:docs/reqcontext.rst+3 added-3 removed
6 unmodified lines7 request. Rather than passing the request object to each function that8 runs during a request, the :data:`request` and :data:`session` proxies9 are accessed instead.10 11-This is similar to the :doc:`/appcontext`, which keeps track of the11+This is similar to :doc:`/appcontext`, which keeps track of the12 application-level data independent of a request. A corresponding13 application context is pushed when a request context is pushed.14 15 16 unmodified lines32 Lifetime of the Context33 -----------------------34 35 When a Flask application begins handling a request, it pushes a request36-context, which also pushes an :doc:`/appcontext`. When the request ends37-it pops the request context then the application context.36+context, which also pushes an :doc:`app context </appcontext>`. When the37+request ends it pops the request context then the application context.38 39 The context is unique to each thread (or other worker type).40 :data:`request` cannot be passed to another thread, the other thread41 will have a different context stack and will not know about the request224 unmodified linesmodified:docs/shell.rst+1 added-2 removed
19 unmodified lines20 that these functions are not only there for interactive shell usage, but21 also for unit testing and other situations that require a faked request22 context.23 24-Generally it's recommended that you read the :doc:`reqcontext`25-chapter of the documentation first.24+Generally it's recommended that you read :doc:`reqcontext` first.25 26 Command Line Interface27 ----------------------28 72 unmodified linesmodified:src/flask/app.py+59 added-61 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:289 unmodified lines360 #:361 #: .. versionadded:: 1.1.0362 url_map_class = Map363 369- #: the test client that is used with when `test_client` is used.364+ #: The :meth:`test_client` method creates an instance of this test365+ #: client class. Defaults to :class:`~flask.testing.FlaskClient`.366 #:367 #: .. versionadded:: 0.7368 test_client_class: t.Optional[t.Type["FlaskClient"]] = None369 369 unmodified lines739 740 :param context: the context as a dictionary that is updated in place741 to add extra variables.742 """747- funcs: t.Iterable[748- TemplateContextProcessorCallable749- ] = self.template_context_processors[None]750- reqctx = _request_ctx_stack.top751- if reqctx is not None:752- for bp in request.blueprints:753- if bp in self.template_context_processors:754- 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()756- for func in funcs:757- context.update(func())758- # make sure the original values win. This makes it possible to759- # easier add new variables in context processors without breaking760- # 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 1281- for c in [code, None] if code is not None else [None]:1282- 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 """1802- 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:1805- # This is called by url_for, which can be called outside a1806- # request, can't use request.blueprints.1807- bps = _split_blueprint_path(endpoint.rpartition(".")[0])1808- bp_funcs = chain.from_iterable(self.url_default_functions[bp] for bp in bps)1809- funcs = chain(funcs, bp_funcs)1805+ names = chain(1806+ names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))1807+ )1808 1811- for func in funcs:1812- 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 1848- funcs: t.Iterable[URLValuePreprocessorCallable] = self.url_value_preprocessors[1849- None1850- ]1851- for bp in request.blueprints:1852- if bp in self.url_value_preprocessors:1853- funcs = chain(funcs, self.url_value_preprocessors[bp])1854- for func in funcs:1855- 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 1857- funcs: t.Iterable[BeforeRequestCallable] = self.before_request_funcs[None]1858- for bp in request.blueprints:1859- if bp in self.before_request_funcs:1860- funcs = chain(funcs, self.before_request_funcs[bp])1861- for func in funcs:1862- rv = self.ensure_sync(func)()1863- if rv is not None:1864- 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.top1882- funcs: t.Iterable[AfterRequestCallable] = ctx._after_request_functions1883- for bp in request.blueprints:1884- if bp in self.after_request_funcs:1885- funcs = chain(funcs, reversed(self.after_request_funcs[bp]))1886- if None in self.after_request_funcs:1887- funcs = chain(funcs, reversed(self.after_request_funcs[None]))1888- for handler in funcs:1889- 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]1919- funcs: t.Iterable[TeardownCallable] = reversed(1920- self.teardown_request_funcs[None]1921- )1922- for bp in request.blueprints:1923- if bp in self.teardown_request_funcs:1924- funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1925- for func in funcs:1926- 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
27 unmodified lines28 - Correctly handle raising deferred errors in CLI lazy loading.29 :issue:`4096`30 - The CLI loader handles ``**kwargs`` in a ``create_app`` function.31 :issue:`4170`32+- Fix the order of ``before_request`` and other callbacks that trigger33+ before the view returns. They are called from the app down to the34+ closest nested blueprint. :issue:`4229`35 36 37 Version 2.0.138 -------------1154 unmodified lines