How to use state handlers to trigger a email notif...
# prefect-community
d
How to use state handlers to trigger a email notification upon failure of a flow ? I am looing for some documentation on this. An example could also help. thanks
1
s
An easy way to incorporate email notifications is to create an automations that sends a notification upon a failure on that specific flow. You can compound actions as well on an automation, or you can merely create a notification within the UI.
b
Here's an example you can adapt to your use case:
Copy code
from prefect import task, flow
from prefect.blocks.notifications import SlackWebhook
from prefect.orion.schemas.states import StateType
import time

#Load your desired block, this example uses a slack notification block.
def notify_function():
    slack_webhook_block = SlackWebhook.load("my-test-notification")
    #This is the message you want to send to slack
    slack_webhook_block.notify("Hello from Prefect!")

#A simple flow
@flow
def my_flow():
   time.sleep(10)
   raise Exception

if __name__ == "__main__":
    #Store the state of your flow
    state = my_flow(return_state=True)
    '''This if statement checks for a specific flow state.
    If the condition is satisfied, the block is invoked.
    State type can be set to any available state type: <https://docs.prefect.io/concepts/states/#state-types''>'
    if state.type == (StateType.FAILED):
        notify_function()
d
thanks @Bianca Hoch and @Sahil Rangwala