https://prefect.io logo
Title
d

darshan darshan

04/13/2023, 12:02 PM
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

Sahil Rangwala

04/13/2023, 4:47 PM
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

Bianca Hoch

04/13/2023, 5:29 PM
Here's an example you can adapt to your use case:
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

darshan darshan

04/14/2023, 10:22 AM
thanks @Bianca Hoch and @Sahil Rangwala