remove uses of LocalStack
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 · parent d597db6 · Browse files · 13 files·+114 added−131 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+114 added−131 removed
- tests:+44 added−50 removed
- other:+70 added−81 removed
Provenance
- Commit
82c2e03- Tree
db4d9f3- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
d597db6
13 files changed+114 added−131 removed
modified:src/flask/app.py+15 added-13 removed
36 unmodified lines37 from .config import ConfigAttribute38 from .ctx import _AppCtxGlobals39 from .ctx import AppContext40 from .ctx import RequestContext41-from .globals import _app_ctx_stack42-from .globals import _request_ctx_stack41+from .globals import _cv_app42+from .globals import _cv_req43 from .globals import g44 from .globals import request45+from .globals import request_ctx46 from .globals import session47 from .helpers import _split_blueprint_path48 from .helpers import get_debug_flag49 from .helpers import get_env1504 unmodified lines1554 .. versionchanged:: 0.71555 This no longer does the exception handling, this code was1556 moved to the new :meth:`full_dispatch_request`.1557 """1557- req = _request_ctx_stack.top.request1558+ req = request_ctx.request1559 if req.routing_exception is not None:1560 self.raise_routing_exception(req)1560- rule = req.url_rule1561+ rule: Rule = req.url_rule # type: ignore[assignment]1562 # if we provide automatic options for this URL and the1563 # request came with the OPTIONS method, reply automatically1564 if (1565 getattr(rule, "provide_automatic_options", False)1566 and req.method == "OPTIONS"1567 ):1568 return self.make_default_options_response()1569 # otherwise dispatch to the handler for that endpoint1570+ view_args: t.Dict[str, t.Any] = req.view_args # type: ignore[assignment]1569- return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)1571+ return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)1572 1573 def full_dispatch_request(self) -> Response:1574 """Dispatches the request and on top of that performs request1575 pre and postprocessing as well as HTTP exception catching and56 unmodified lines1632 behavior of ``OPTIONS`` responses.1633 1634 .. versionadded:: 0.71635 """1634- adapter = _request_ctx_stack.top.url_adapter1635- methods = adapter.allowed_methods()1636+ adapter = request_ctx.url_adapter1637+ methods = adapter.allowed_methods() # type: ignore[union-attr]1638 rv = self.response_class()1639 rv.allow.update(methods)1640 return rv1641 99 unmodified lines1741 1742 .. versionadded:: 2.21743 Moved from ``flask.url_for``, which calls this method.1744 """1743- req_ctx = _request_ctx_stack.top1745+ req_ctx = _cv_req.get(None)1746 1747 if req_ctx is not None:1748 url_adapter = req_ctx.url_adapter1749 blueprint_name = req_ctx.request.blueprint10 unmodified lines1760 # domain by default, unless a scheme is given.1761 if _external is None:1762 _external = _scheme is not None1763 else:1762- app_ctx = _app_ctx_stack.top1764+ app_ctx = _cv_app.get(None)1765 1766 # If called by helpers.url_for, an app context is active,1767 # use its url_adapter. Otherwise, app.url_for was called1768 # directly, build an adapter.22 unmodified lines1791 1792 self.inject_url_defaults(endpoint, values)1793 1794 try:1793- rv = url_adapter.build(1795+ rv = url_adapter.build( # type: ignore[union-attr]1796 endpoint,1797 values,1798 method=_method,1799 url_scheme=_scheme,300 unmodified lines2100 :param response: a :attr:`response_class` object.2101 :return: a new response object or the same, has to be an2102 instance of :attr:`response_class`.2103 """2102- ctx = _request_ctx_stack.top2104+ ctx = request_ctx._get_current_object() # type: ignore[attr-defined]2105 2106 for func in ctx._after_request_functions:2107 response = self.ensure_sync(func)(response)2108 197 unmodified lines2306 raise2307 return response(environ, start_response)2308 finally:2309 if "werkzeug.debug.preserve_context" in environ:2308- environ["werkzeug.debug.preserve_context"](_app_ctx_stack.top)2309- environ["werkzeug.debug.preserve_context"](_request_ctx_stack.top)2310+ environ["werkzeug.debug.preserve_context"](_cv_app.get())2311+ environ["werkzeug.debug.preserve_context"](_cv_req.get())2312 2313 if error is not None and self.should_ignore_error(error):2314 error = None2315 8 unmodified linesmodified:src/flask/cli.py+3 added-5 removed
1049 unmodified lines1050 This is useful for executing small snippets of management code1051 without having to manually configure the application.1052 """1053 import code1054- from .globals import _app_ctx_stack1054 1056- app = _app_ctx_stack.top.app1055 banner = (1056 f"Python {sys.version} on {sys.platform}\n"1059- f"App: {app.import_name} [{app.env}]\n"1060- f"Instance: {app.instance_path}"1057+ f"App: {current_app.import_name} [{current_app.env}]\n"1058+ f"Instance: {current_app.instance_path}"1059 )1060 ctx: dict = {}1061 1062 # Support the regular Python interpreter startup script if someone2 unmodified lines1065 if startup and os.path.isfile(startup):1066 with open(startup) as f:1067 eval(compile(f.read(), startup, "exec"), ctx)1068 1071- ctx.update(app.make_shell_context())1069+ ctx.update(current_app.make_shell_context())1070 1071 # Site, customize, or startup script can set a hook to call when1072 # entering interactive mode. The default one sets up readline with1073 # tab and history completion.85 unmodified linesmodified:src/flask/ctx.py+19 added-21 removed
5 unmodified lines6 7 from werkzeug.exceptions import HTTPException8 9 from . import typing as ft10-from .globals import _app_ctx_stack10 from .globals import _cv_app11 from .globals import _cv_req13-from .globals import _request_ctx_stack12 from .signals import appcontext_popped13 from .signals import appcontext_pushed14 15 if t.TYPE_CHECKING: # pragma: no cover87 unmodified lines103 def __iter__(self) -> t.Iterator[str]:104 return iter(self.__dict__)105 106 def __repr__(self) -> str:109- top = _app_ctx_stack.top110- if top is not None:111- return f"<flask.g of {top.app.name!r}>"107+ ctx = _cv_app.get(None)108+ if ctx is not None:109+ return f"<flask.g of '{ctx.app.name}'>"110 return object.__repr__(self)111 112 113 def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:16 unmodified lines130 some headers without converting the return value into a response object.131 132 .. versionadded:: 0.9133 """136- top = _request_ctx_stack.top134+ ctx = _cv_req.get(None)135 138- if top is None:136+ if ctx is None:137 raise RuntimeError(140- "This decorator can only be used when a request context is"141- " active, such as within a view function."138+ "'after_this_request' can only be used when a request"139+ " context is active, such as in a view function."140 )141 144- top._after_request_functions.append(f)142+ ctx._after_request_functions.append(f)143 return f144 145 146 def copy_current_request_context(f: t.Callable) -> t.Callable:19 unmodified lines166 return 'Regular response'167 168 .. versionadded:: 0.10169 """172- top = _request_ctx_stack.top170+ ctx = _cv_req.get(None)171 174- if top is None:172+ if ctx is None:173 raise RuntimeError(176- "This decorator can only be used when a request context is"177- " active, such as within a view function."174+ "'copy_current_request_context' can only be used when a"175+ " request context is active, such as in a view function."176 )177 180- reqctx = top.copy()178+ ctx = ctx.copy()179 180 def wrapper(*args, **kwargs):183- with reqctx:184- return reqctx.app.ensure_sync(f)(*args, **kwargs)181+ with ctx:182+ return ctx.app.ensure_sync(f)(*args, **kwargs)183 184 return update_wrapper(wrapper, f)185 186 50 unmodified lines237 238 def __init__(self, app: "Flask") -> None:239 self.app = app240 self.url_adapter = app.create_url_adapter(None)243- self.g = app.app_ctx_globals_class()241+ self.g: _AppCtxGlobals = app.app_ctx_globals_class()242 self._cv_tokens: t.List[contextvars.Token] = []243 244 def push(self) -> None:245 """Binds the app context to the current context."""62 unmodified lines308 ) -> None:309 self.app = app310 if request is None:311 request = app.request_class(environ)314- self.request = request312+ self.request: Request = request313 self.url_adapter = None314 try:315 self.url_adapter = app.create_url_adapter(self.request)316 except HTTPException as e:317 self.request.routing_exception = e320- self.flashes = None321- self.session = session318+ self.flashes: t.Optional[t.List[t.Tuple[str, str]]] = None319+ self.session: t.Optional["SessionMixin"] = session320 # Functions that should be executed after the request on the response321 # object. These will be called before the regular "after_request"322 # functions.323 self._after_request_functions: t.List[ft.AfterRequestCallable] = []116 unmodified linesmodified:src/flask/debughelpers.py+3 added-4 removed
1 import typing as t2 3 from .app import Flask4 from .blueprints import Blueprint5-from .globals import _request_ctx_stack5+from .globals import request_ctx6 7 8 class UnexpectedUnicodeError(AssertionError, UnicodeError):9 """Raised in places where we want some better error reporting for105 unmodified lines115 """This should help developers understand what failed"""116 info = [f"Locating template {template!r}:"]117 total_found = 0118 blueprint = None119- reqctx = _request_ctx_stack.top120- if reqctx is not None and reqctx.request.blueprint is not None:121- blueprint = reqctx.request.blueprint119+ if request_ctx and request_ctx.request.blueprint is not None:120+ blueprint = request_ctx.request.blueprint121 122 for idx, (loader, srcobj, triple) in enumerate(attempts):123 if isinstance(srcobj, Flask):124 src_info = f"application {srcobj.import_name!r}"34 unmodified linesmodified:src/flask/helpers.py+8 added-8 removed
10 unmodified lines11 import werkzeug.utils12 from werkzeug.exceptions import abort as _wz_abort13 from werkzeug.utils import redirect as _wz_redirect14 15-from .globals import _request_ctx_stack15+from .globals import _cv_req16 from .globals import current_app17 from .globals import request18+from .globals import request_ctx19 from .globals import session20 from .signals import message_flashed21 22 if t.TYPE_CHECKING: # pragma: no cover87 unmodified lines110 111 return update_wrapper(decorator, generator_or_function) # type: ignore112 113 def generator() -> t.Generator:113- ctx = _request_ctx_stack.top114+ ctx = _cv_req.get(None)115 if ctx is None:116 raise RuntimeError(116- "Attempted to stream with context but "117- "there was no context in the first place to keep around."117+ "'stream_with_context' can only be used when a request"118+ " context is active, such as in a view function."119 )120 with ctx:121 # Dummy sentinel. Has to be inside the context block or we're122 # not actually keeping the context around.254 unmodified lines377 :param with_categories: set to ``True`` to also receive categories.378 :param category_filter: filter of categories to limit return values. Only379 categories in the list will be returned.380 """380- flashes = _request_ctx_stack.top.flashes381+ flashes = request_ctx.flashes382 if flashes is None:382- _request_ctx_stack.top.flashes = flashes = (383- session.pop("_flashes") if "_flashes" in session else []384- )383+ flashes = session.pop("_flashes") if "_flashes" in session else []384+ request_ctx.flashes = flashes385 if category_filter:386 flashes = list(filter(lambda f: f[0] in category_filter, flashes))387 if not with_categories:388 return [x[1] for x in flashes]298 unmodified linesmodified:src/flask/templating.py+21 added-29 removed
3 unmodified lines4 from jinja2 import Environment as BaseEnvironment5 from jinja2 import Template6 from jinja2 import TemplateNotFound7 8-from .globals import _app_ctx_stack9-from .globals import _request_ctx_stack8+from .globals import _cv_app9+from .globals import _cv_req10 from .globals import current_app11 from .globals import request12 from .helpers import stream_with_context13 from .signals import before_render_template7 unmodified lines21 def _default_template_ctx_processor() -> t.Dict[str, t.Any]:22 """Default template context processor. Injects `request`,23 `session` and `g`.24 """25- reqctx = _request_ctx_stack.top26- appctx = _app_ctx_stack.top27- rv = {}25+ appctx = _cv_app.get(None)26+ reqctx = _cv_req.get(None)27+ rv: t.Dict[str, t.Any] = {}28 if appctx is not None:29 rv["g"] = appctx.g30 if reqctx is not None:31 rv["request"] = reqctx.request91 unmodified lines123 124 return list(result)125 126 127-def _render(template: Template, context: dict, app: "Flask") -> str:127+def _render(app: "Flask", template: Template, context: t.Dict[str, t.Any]) -> str:128+ app.update_template_context(context)129 before_render_template.send(app, template=template, context=context)130 rv = template.render(context)131 template_rendered.send(app, template=template, context=context)132 return rv2 unmodified lines135 def render_template(136 template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]],137 **context: t.Any138 ) -> str:138- """Renders a template from the template folder with the given139- context.139+ """Render a template by name with the given context.140 141- :param template_name_or_list: the name of the template to be142- rendered, or an iterable with template names143- the first one existing will be rendered144- :param context: the variables that should be available in the145- context of the template.141+ :param template_name_or_list: The name of the template to render. If142+ a list is given, the first name to exist will be rendered.143+ :param context: The variables to make available in the template.144 """147- ctx = _app_ctx_stack.top148- ctx.app.update_template_context(context)149- return _render(150- ctx.app.jinja_env.get_or_select_template(template_name_or_list),151- context,152- ctx.app,153- )145+ app = current_app._get_current_object() # type: ignore[attr-defined]146+ template = app.jinja_env.get_or_select_template(template_name_or_list)147+ return _render(app, template, context)148 149 150 def render_template_string(source: str, **context: t.Any) -> str:157- """Renders a template from the given template source string158- with the given context. Template variables will be autoescaped.151+ """Render a template from the given source string with the given152+ context.153 160- :param source: the source code of the template to be161- rendered162- :param context: the variables that should be available in the163- context of the template.154+ :param source: The source code of the template to render.155+ :param context: The variables to make available in the template.156 """165- ctx = _app_ctx_stack.top166- ctx.app.update_template_context(context)167- return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)157+ app = current_app._get_current_object() # type: ignore[attr-defined]158+ template = app.jinja_env.from_string(source)159+ return _render(app, template, context)160 161 162 def _stream(163 app: "Flask", template: Template, context: t.Dict[str, t.Any]49 unmodified linesmodified:src/flask/testing.py+1 added-1 removed
161 unmodified lines162 # (or None) on top of this and popping it we get exactly that163 # behavior. It's important to not use the push and pop164 # methods of the actual request context object since that would165 # mean that cleanup handlers are called166- token = _cv_req.set(outer_reqctx)166+ token = _cv_req.set(outer_reqctx) # type: ignore[arg-type]167 try:168 yield sess169 finally:170 _cv_req.reset(token)118 unmodified linesmodified:tests/conftest.py+10 added-9 removed
4 unmodified lines5 6 import pytest7 from _pytest import monkeypatch8 9-import flask10-from flask import Flask as _Flask9+from flask import Flask10+from flask.globals import request_ctx11 12 13 @pytest.fixture(scope="session", autouse=True)14 def _standard_os_environ():28 unmodified lines43 """44 monkeypatch._setitem.extend(_standard_os_environ)45 46 47-class Flask(_Flask):48- testing = True49- secret_key = "test key"50-51-47 @pytest.fixture48 def app():49 app = Flask("flask_test", root_path=os.path.dirname(__file__))50+ app.config.update(51+ TESTING=True,52+ SECRET_KEY="test key",53+ )54 return app55 56 57 @pytest.fixture32 unmodified lines90 91 # make sure we're not leaking a request context since we are92 # testing flask internally in debug mode in a few cases93 leaks = []95- while flask._request_ctx_stack.top is not None:96- leaks.append(flask._request_ctx_stack.pop())94+ while request_ctx:95+ leaks.append(request_ctx._get_current_object())96+ request_ctx.pop()97+98 assert leaks == []99 100 101 @pytest.fixture(params=(True, False))98 unmodified linesmodified:tests/test_appctx.py+10 added-8 removed
1 import pytest2 3 import flask4+from flask.globals import app_ctx5+from flask.globals import request_ctx6 7 8 def test_basic_url_generation(app):9 app.config["SERVER_NAME"] = "localhost"20 unmodified lines30 31 32 def test_request_context_means_app_context(app):33 with app.test_request_context():32- assert flask.current_app._get_current_object() == app33- assert flask._app_ctx_stack.top is None34+ assert flask.current_app._get_current_object() is app35+ assert not flask.current_app36 37 38 def test_app_context_provides_current_app(app):39 with app.app_context():38- assert flask.current_app._get_current_object() == app39- assert flask._app_ctx_stack.top is None40+ assert flask.current_app._get_current_object() is app41+ assert not flask.current_app42 43 44 def test_app_tearing_down(app):45 cleanup_stuff = []130 unmodified lines176 called.append("app")177 178 @app.route("/")179 def index():178- with flask._app_ctx_stack.top:179- with flask._request_ctx_stack.top:180+ with app_ctx:181+ with request_ctx:182 pass181- env = flask._request_ctx_stack.top.request.environ182- assert env["werkzeug.request"] is not None183+184+ assert flask.request.environ["werkzeug.request"] is not None185 return ""186 187 res = client.get("/")188 assert res.status_code == 20024 unmodified linesmodified:tests/test_basic.py+17 added-29 removed
1108 unmodified lines1109 @app.route("/fail", methods=["POST"])1110 def index():1111 return flask.request.files["foo"].filename1112 1113- # with statement is important because we leave an exception on the1114- # stack otherwise and we want to ensure that this is not the case1115- # to not negatively affect other tests.1116- with client:1117- with pytest.raises(DebugFilesKeyError) as e:1118- client.post("/fail", data={"foo": "index.txt"})1119- assert "no file contents were transmitted" in str(e.value)1120- assert "This was submitted: 'index.txt'" in str(e.value)1113+ with pytest.raises(DebugFilesKeyError) as e:1114+ client.post("/fail", data={"foo": "index.txt"})1115+ assert "no file contents were transmitted" in str(e.value)1116+ assert "This was submitted: 'index.txt'" in str(e.value)1117 1118 1119 def test_response_types(app, client):1120 @app.route("/text")422 unmodified lines1543 rv = client.get("/", "http://foo.dev.local")1544 assert rv.data == b"subdomain"1545 1546 1551-@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")1552-@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")1553-def test_exception_propagation(app, client):1554- def apprunner(config_key):1555- @app.route("/")1556- def index():1557- 1 // 01547+@pytest.mark.parametrize("key", ["TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None])1548+def test_exception_propagation(app, client, key):1549+ app.testing = False1550 1559- if config_key is not None:1560- app.config[config_key] = True1561- with pytest.raises(Exception):1562- client.get("/")1563- else:1564- assert client.get("/").status_code == 5001551+ @app.route("/")1552+ def index():1553+ 1 // 01554 1566- # we have to run this test in an isolated thread because if the1567- # debug flag is set to true and an exception happens the context is1568- # not torn down. This causes other tests that run after this fail1569- # when they expect no exception on the stack.1570- for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1571- t = Thread(target=apprunner, args=(config_key,))1572- t.start()1573- t.join()1555+ if key is not None:1556+ app.config[key] = True1557 1558+ with pytest.raises(ZeroDivisionError):1559+ client.get("/")1560+ else:1561+ assert client.get("/").status_code == 5001562 1563+1564 @pytest.mark.parametrize("debug", [True, False])1565 @pytest.mark.parametrize("use_debugger", [True, False])1566 @pytest.mark.parametrize("use_reloader", [True, False])1567 @pytest.mark.parametrize("propagate_exceptions", [None, True, False])402 unmodified linesmodified:tests/test_reqctx.py+3 added-2 removed
1 unmodified line2 3 import pytest4 5 import flask6+from flask.globals import request_ctx7 from flask.sessions import SecureCookieSessionInterface8 from flask.sessions import SessionInterface9 10 try:105 unmodified lines116 with app.test_request_context("/?name=World"):117 assert index() == "Hello World!"118 with app.test_request_context("/meh"):119 assert meh() == "http://localhost/meh"119- assert flask._request_ctx_stack.top is None120+ assert not flask.request121 122 123 def test_context_test(app):124 assert not flask.request27 unmodified lines152 153 @app.route("/")154 def index():155 flask.session["fizz"] = "buzz"155- reqctx = flask._request_ctx_stack.top.copy()156+ reqctx = request_ctx.copy()157 158 def g():159 assert not flask.request160 assert not flask.current_app166 unmodified linesmodified:tests/test_session_interface.py+2 added-1 removed
1 import flask2+from flask.globals import request_ctx3 from flask.sessions import SessionInterface4 5 6 def test_open_session_with_endpoint():6 unmodified lines13 def save_session(self, app, session, response):14 pass15 16 def open_session(self, app, request):16- flask._request_ctx_stack.top.match_request()17+ request_ctx.match_request()18 assert request.endpoint is not None19 20 app = flask.Flask(__name__)21 app.session_interface = MySessionInterface()7 unmodified linesmodified:tests/test_testing.py+2 added-1 removed
3 unmodified lines4 5 import flask6 from flask import appcontext_popped7 from flask.cli import ScriptInfo8+from flask.globals import _cv_req9 from flask.json import jsonify10 from flask.testing import EnvironBuilder11 from flask.testing import FlaskCliRunner12 386 unmodified lines399 400 # close the response, releasing the context held by stream_with_context401 rv.close()402 # only req_ctx fixture should still be pushed402- assert flask._request_ctx_stack.top is req_ctx403+ assert _cv_req.get(None) is req_ctx