From 331616b19a843c541ee395bf46d754074eecddf8 Mon Sep 17 00:00:00 2001 From: Joel Tetrault Date: Wed, 19 Feb 2020 10:05:22 -0600 Subject: [PATCH] changes to make app.current_request thread safe when running chalice locally - fixes race conditions that can occur when chalice is being run locally and it handling multiple concurrent requests --- chalice/local.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/chalice/local.py b/chalice/local.py index f6ce45102f..3826df972c 100644 --- a/chalice/local.py +++ b/chalice/local.py @@ -47,7 +47,10 @@ def time(self): def create_local_server(app_obj, config, host, port): # type: (Chalice, Config, str, int) -> LocalDevServer - return LocalDevServer(app_obj, config, host, port) + local_app_opj = app_obj # type: LocalChalice + local_app_opj.__class__ = LocalChalice + local_app_opj.initialize_current_request_lookup() + return LocalDevServer(local_app_opj, config, host, port) class LocalARNBuilder(object): @@ -661,3 +664,28 @@ def shutdown(self): # type: () -> None if self._server is not None: self._server.shutdown() + + +class LocalChalice(Chalice): + def __init__(self, *args, **kwargs): + # type: (Any, Any) -> None + self._current_request_lookup = {} # type: Dict[int, dict] + super(LocalChalice, self).__init__(*args, **kwargs) + + def initialize_current_request_lookup(self): + # type: () -> None + self._current_request_lookup = {} + + @property + def current_request(self): # noqa + # type: () -> Optional[Request] + thread_id = threading.current_thread().ident + assert thread_id is not None + return self._current_request_lookup.get(thread_id, None) + + @current_request.setter + def current_request(self, value): # noqa + # type: (Request) -> None + thread_id = threading.current_thread().ident + assert thread_id is not None + self._current_request_lookup[thread_id] = value