Zach
06/18/2024, 5:58 PMMarvin
06/18/2024, 5:58 PMfail
method provided by the Prefect API. Here is an example to illustrate how you can achieve this:
### To cancel a task:
You can raise an exception to mark a task as failed:
python
from prefect import flow, task
@task
def check_condition_and_fail():
condition = True # Replace with your actual condition
if condition:
raise ValueError("Condition met, cancelling the task.")
return "Continue execution"
@flow
def my_flow():
try:
check_condition_and_fail()
except ValueError as e:
print(e)
return # Optionally perform cleanup or other actions
if __name__ == "__main__":
my_flow()
### To cancel a flow:
You can set the state to Cancelled
when a specific condition is met:
python
from prefect import flow, task
from prefect.engine import signals
@task
def some_task():
return True # Replace with your actual task logic
@flow
def my_flow():
if some_task():
raise signals.FAIL("Condition met, cancelling the flow.")
return "Flow completed successfully"
if __name__ == "__main__":
my_flow()
In this example, if the condition is met, a ValueError
is raised, marking the task as failed, and the flow returns. For flows, throwing a FAIL
signal achieves a similar intent by marking the flow as failed.
### Reference
For further details, check the official Prefect documentation:
- Prefect Flows
- Prefect Tasks