Skip to content

Commit ea68ea7

Browse files
committed
Apply request context to task target in correct thread
1 parent 0c98719 commit ea68ea7

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

labthings/core/tasks/thread.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ def __init__(self, target, *args, **kwargs):
3333
self._args = args
3434
self._kwargs = kwargs
3535

36+
# copy_current_request_context allows threads to access flask current_app
37+
if has_request_context():
38+
logging.debug(f"Copying request context to {self._target}")
39+
self._target = copy_current_request_context(self._target)
40+
else:
41+
logging.debug("No request context to copy")
42+
3643
# Nice string representation of target function
3744
self.target_string = f"{self._target}(args={self._args}, kwargs={self._kwargs})"
3845

@@ -79,12 +86,7 @@ def update_data(self, data: dict):
7986
self.data.update(data)
8087

8188
def _run(self): # pylint: disable=E0202
82-
# copy_current_request_context allows threads to access flask current_app
83-
if has_request_context():
84-
target = copy_current_request_context(self._target)
85-
else:
86-
target = self._target
87-
return self._thread_proc(target)(*self._args, **self._kwargs)
89+
return self._thread_proc(self._target)(*self._args, **self._kwargs)
8890

8991
def _thread_proc(self, f):
9092
"""

0 commit comments

Comments
 (0)