Does anyone know the preferred way to get the stat...
# prefect-community
d
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
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
@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
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
I'm am developing on server but will run production in cloud.
a
what's your alerting solution? Slack, Teams, Email, Pagerduty?
d
I don't know if it is a case of alert. I see it as more of post workflow processing.
Internal proprietary (sigh!)
k
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
Where is the State imported from?
i.e. from prefect.xx import State?
k
prefect.engine
d
tnx
k
You can find that here
a
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
Thanks a bunch. I'll look into them.
👍 1