Reputation: 131
I'm not sure if this is possible, since flow names are assigned later when a flow is actually run (aka, "creepy-lemur" or whatnot), but I'd like to define a Prefect task within a flow and have that task collect the name of the flow that ran it, so I can insert it into a database table. Has anyone figured out how to do this?
Upvotes: 3
Views: 3826
Reputation: 12018
Additionally, you can also access this information from the runtime
context object/module (introduced in Prefect 2):
from prefect import flow, task
from prefect import runtime
@task
def my_task():
task_name = runtime.task_run.name
flow_run_name = runtime.flow_run.name
Upvotes: 2
Reputation: 41
For anyone facing this issue with prefect 2, you can import the FlowRunContext from a task like this:
from prefect.context import FlowRunContext
@task
def my_task():
flow_run_name = FlowRunContext.get().flow_run.dict().get('name')
Source: https://docs.prefect.io/latest/concepts/runtime-context/
Upvotes: 4
Reputation: 1758
You can get the flow run name and ID from the context:
import prefect
from prefect import task, flow
@task
def print_task_context():
print("Task run context:")
print(prefect.context.get_run_context().task_run.dict())
@flow
def main_flow():
print_task_context()
print("Flow run context:")
print(prefect.context.get_run_context().flow_run.dict())
if __name__ == "__main__":
main_flow()
Here are more resources on Prefect Discourse about setting custom run names:
Upvotes: 6