Blake
04/15/2024, 2:53 PMMarvin
04/15/2024, 2:54 PMprefect.context
module to access the current run context with prefect.context.get_run_context()
. If you are within a flow or task run, this function will provide the context, and if a task run context is available, it will be returned even if a flow run context is also available.
Here's a snippet from the Prefect documentation that explains how to access the run context, including explicit access to the flow run or task run context:
python
from prefect.context import FlowRunContext, TaskRunContext
flow_run_ctx = FlowRunContext.get()
task_run_ctx = TaskRunContext.get()
Note that get_run_context
, FlowRunContext.get()
, and TaskRunContext.get()
might return None
if the context is not available, but they will not raise an error.
To use this in a thread, make sure to capture the context outside of the thread and then pass it as an argument to the target function being executed by the thread. This is necessary because Prefect contexts are not inherently thread-safe and may not be available directly within a new thread.
Here is an example based on the information provided in the documentation:
python
import threading
from prefect import flow
from prefect.context import get_run_context
@flow
def main_flow():
# Get the current run context before creating a thread
flow_context = get_run_context()
# Function that will be run in a thread, takes the context as an argument
def thread_function(ctx):
# Use the provided context here
pass
# Create and start a thread, passing the captured context
thread = threading.Thread(target=thread_function, args=(flow_context,))
thread.start()
thread.join()
# Run the flow
main_flow()
Below are the relevant links to the Prefect documentation and a related GitHub issue:
- Runtime Context in Prefect documentation
- GitHub issue regarding logging context with DaskTaskRunner and Task.map
- Concurrency limits in Prefect documentation (Note: this is less related but found in the search)
Remember that this context passing strategy is for manual thread management. Prefect also has native support for concurrency using `TaskRunner`s like ConcurrentTaskRunner
, which manages the context for you when it runs tasks concurrently.Blake
04/15/2024, 2:57 PMMarvin
04/15/2024, 2:58 PM