https://prefect.io logo
#prefect-community
Title
# prefect-community
d

David Haynes

04/11/2022, 6:20 PM
Does anyone know the preferred way to get the state of a Flow after execution? I tried to write a terminal_state_handler but cannot find how to import the 'State' module. Is this even the correct approach or is there another way that is better?
a

Anna Geller

04/11/2022, 6:23 PM
Can you explain your use case first? What would you want to accomplish with such a state handler?
to answer directly: you can import any state from
prefect.engine
e.g.:
Copy code
from prefect.engine.state import Failed, Retrying, ...
d

David Haynes

04/11/2022, 6:31 PM
@Anna Geller Thanks. My use case is that I want to capture whether a flow has succeeded or failed in our internal monitoring tool For this, I would need to determine the SUCCESS or FAIL status of the workflow. I think it means I need to define a terminal_state_handler and walk the task-states to see if there is a case where 'is_failed()' is true. My question was really about whether this was the best/preferred way of doing this.
a

Anna Geller

04/11/2022, 6:33 PM
glad you explained your use case more! so your end goal would be to get an alert when a flow run fails? are you on Prefect Cloud or Server?
d

David Haynes

04/11/2022, 6:33 PM
I'm am developing on server but will run production in cloud.
a

Anna Geller

04/11/2022, 6:34 PM
what's your alerting solution? Slack, Teams, Email, Pagerduty?
d

David Haynes

04/11/2022, 6:34 PM
I don't know if it is a case of alert. I see it as more of post workflow processing.
Internal proprietary (sigh!)
k

Kevin Kho

04/11/2022, 6:34 PM
Just use a vanilla state handler attached to the flow:
Copy code
def state_handler(obj: Flow, old_state: State, new_state: State) -> Optional[State]:
    """
    if new_state.is_finished():
        if new_state.is_failed():
            ....
        if new_state.is_successful():
            ....
    return new_state
d

David Haynes

04/11/2022, 6:35 PM
Where is the State imported from?
i.e. from prefect.xx import State?
k

Kevin Kho

04/11/2022, 6:36 PM
prefect.engine
d

David Haynes

04/11/2022, 6:36 PM
tnx
k

Kevin Kho

04/11/2022, 6:36 PM
You can find that here
a

Anna Geller

04/11/2022, 6:36 PM
as Kevin mentioned, there are 2 options for alerting on failed flow run: one would be via a flow-level state handler (make sure to attach it to your Flow object, rather than to a task) as above and another via a Cloud Hook https://docs.prefect.io/orchestration/concepts/cloud_hooks.html#cloud-hooks
d

David Haynes

04/11/2022, 6:37 PM
Thanks a bunch. I'll look into them.
👍 1
5 Views