Skip to content
Myr

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

13 files+114 added−131 removed

modified:src/flask/app.py+15 added-13 removed
36 unmodified lines
37from .config import ConfigAttribute38from .ctx import _AppCtxGlobals39from .ctx import AppContext40from .ctx import RequestContext41from .globals import _app_ctx_stack42from .globals import _request_ctx_stack41from .globals import _cv_app42from .globals import _cv_req43from .globals import g44from .globals import request45from .globals import request_ctx46from .globals import session47from .helpers import _split_blueprint_path48from .helpers import get_debug_flag49from .helpers import get_env
1504 unmodified lines
1554 .. 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)15721573 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 and
56 unmodified lines
1632 behavior of ``OPTIONS`` responses.16331634 .. 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 lines
17411742 .. 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)17461747 if req_ctx is not None:1748 url_adapter = req_ctx.url_adapter1749 blueprint_name = req_ctx.request.blueprint
10 unmodified lines
1760 # 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)17651766 # 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 lines
17911792 self.inject_url_defaults(endpoint, values)17931794 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 lines
2100 :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]21052106 for func in ctx._after_request_functions:2107 response = self.ensure_sync(func)(response)2108
197 unmodified lines
2306 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())23122313 if error is not None and self.should_ignore_error(error):2314 error = None2315
8 unmodified lines
modified:src/flask/cli.py+3 added-5 removed
1049 unmodified lines
1050 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_stack10541056 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 = {}10611062 # Support the regular Python interpreter startup script if someone
2 unmodified lines
1065 if startup and os.path.isfile(startup):1066 with open(startup) as f:1067 eval(compile(f.read(), startup, "exec"), ctx)10681071 ctx.update(app.make_shell_context())1069 ctx.update(current_app.make_shell_context())10701071 # 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 lines
modified:src/flask/ctx.py+19 added-21 removed
5 unmodified lines
67from werkzeug.exceptions import HTTPException89from . import typing as ft10from .globals import _app_ctx_stack10from .globals import _cv_app11from .globals import _cv_req13from .globals import _request_ctx_stack12from .signals import appcontext_popped13from .signals import appcontext_pushed1415if t.TYPE_CHECKING: # pragma: no cover
87 unmodified lines
103 def __iter__(self) -> t.Iterator[str]:104 return iter(self.__dict__)105106 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)111112113def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:
16 unmodified lines
130 some headers without converting the return value into a response object.131132 .. versionadded:: 0.9133 """136 top = _request_ctx_stack.top134 ctx = _cv_req.get(None)135138 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 )141144 top._after_request_functions.append(f)142 ctx._after_request_functions.append(f)143 return f144145146def copy_current_request_context(f: t.Callable) -> t.Callable:
19 unmodified lines
166 return 'Regular response'167168 .. versionadded:: 0.10169 """172 top = _request_ctx_stack.top170 ctx = _cv_req.get(None)171174 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 )177180 reqctx = top.copy()178 ctx = ctx.copy()179180 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)183184 return update_wrapper(wrapper, f)185186
50 unmodified lines
237238 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] = []243244 def push(self) -> None:245 """Binds the app context to the current context."""
62 unmodified lines
308 ) -> 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 lines
modified:src/flask/debughelpers.py+3 added-4 removed
1import typing as t23from .app import Flask4from .blueprints import Blueprint5from .globals import _request_ctx_stack5from .globals import request_ctx678class UnexpectedUnicodeError(AssertionError, UnicodeError):9 """Raised in places where we want some better error reporting for
105 unmodified lines
115 """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.blueprint121122 for idx, (loader, srcobj, triple) in enumerate(attempts):123 if isinstance(srcobj, Flask):124 src_info = f"application {srcobj.import_name!r}"
34 unmodified lines
modified:src/flask/helpers.py+8 added-8 removed
10 unmodified lines
11import werkzeug.utils12from werkzeug.exceptions import abort as _wz_abort13from werkzeug.utils import redirect as _wz_redirect1415from .globals import _request_ctx_stack15from .globals import _cv_req16from .globals import current_app17from .globals import request18from .globals import request_ctx19from .globals import session20from .signals import message_flashed2122if t.TYPE_CHECKING: # pragma: no cover
87 unmodified lines
110111 return update_wrapper(decorator, generator_or_function) # type: ignore112113 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 lines
377 :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 lines
modified:src/flask/templating.py+21 added-29 removed
3 unmodified lines
4from jinja2 import Environment as BaseEnvironment5from jinja2 import Template6from jinja2 import TemplateNotFound78from .globals import _app_ctx_stack9from .globals import _request_ctx_stack8from .globals import _cv_app9from .globals import _cv_req10from .globals import current_app11from .globals import request12from .helpers import stream_with_context13from .signals import before_render_template
7 unmodified lines
21def _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.request
91 unmodified lines
123124 return list(result)125126127def _render(template: Template, context: dict, app: "Flask") -> str:127def _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 rv
2 unmodified lines
135def 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.140141 :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)148149150def 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.153160 :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)160161162def _stream(163 app: "Flask", template: Template, context: t.Dict[str, t.Any]
49 unmodified lines
modified:src/flask/testing.py+1 added-1 removed
161 unmodified lines
162 # (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 lines
modified:tests/conftest.py+10 added-9 removed
4 unmodified lines
56import pytest7from _pytest import monkeypatch89import flask10from flask import Flask as _Flask9from flask import Flask10from flask.globals import request_ctx111213@pytest.fixture(scope="session", autouse=True)14def _standard_os_environ():
28 unmodified lines
43 """44 monkeypatch._setitem.extend(_standard_os_environ)454647class Flask(_Flask):48 testing = True49 secret_key = "test key"505147@pytest.fixture48def 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 app555657@pytest.fixture
32 unmodified lines
9091 # 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()9798 assert leaks == []99100101@pytest.fixture(params=(True, False))
98 unmodified lines
modified:tests/test_appctx.py+10 added-8 removed
1import pytest23import flask4from flask.globals import app_ctx5from flask.globals import request_ctx678def test_basic_url_generation(app):9 app.config["SERVER_NAME"] = "localhost"
20 unmodified lines
303132def 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_app363738def 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_app424344def test_app_tearing_down(app):45 cleanup_stuff = []
130 unmodified lines
176 called.append("app")177178 @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 None183184 assert flask.request.environ["werkzeug.request"] is not None185 return ""186187 res = client.get("/")188 assert res.status_code == 200
24 unmodified lines
modified:tests/test_basic.py+17 added-29 removed
1108 unmodified lines
1109 @app.route("/fail", methods=["POST"])1110 def index():1111 return flask.request.files["foo"].filename11121113 # 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)111711181119def test_response_types(app, client):1120 @app.route("/text")
422 unmodified lines
1543 rv = client.get("/", "http://foo.dev.local")1544 assert rv.data == b"subdomain"154515461551@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")1552@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")1553def 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])1548def test_exception_propagation(app, client, key):1549 app.testing = False15501559 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 // 015541566 # 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] = True15571558 with pytest.raises(ZeroDivisionError):1559 client.get("/")1560 else:1561 assert client.get("/").status_code == 500156215631564@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 lines
modified:tests/test_reqctx.py+3 added-2 removed
1 unmodified line
23import pytest45import flask6from flask.globals import request_ctx7from flask.sessions import SecureCookieSessionInterface8from flask.sessions import SessionInterface910try:
105 unmodified lines
116 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.request121122123def test_context_test(app):124 assert not flask.request
27 unmodified lines
152153 @app.route("/")154 def index():155 flask.session["fizz"] = "buzz"155 reqctx = flask._request_ctx_stack.top.copy()156 reqctx = request_ctx.copy()157158 def g():159 assert not flask.request160 assert not flask.current_app
166 unmodified lines
modified:tests/test_session_interface.py+2 added-1 removed
1import flask2from flask.globals import request_ctx3from flask.sessions import SessionInterface456def test_open_session_with_endpoint():
6 unmodified lines
13 def save_session(self, app, session, response):14 pass1516 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 None1920 app = flask.Flask(__name__)21 app.session_interface = MySessionInterface()
7 unmodified lines
modified:tests/test_testing.py+2 added-1 removed
3 unmodified lines
45import flask6from flask import appcontext_popped7from flask.cli import ScriptInfo8from flask.globals import _cv_req9from flask.json import jsonify10from flask.testing import EnvironBuilder11from flask.testing import FlaskCliRunner12
386 unmodified lines
399400 # 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