Files
airflow/dags/test/fail_test.py
T
2025-04-23 15:47:44 +08:00

43 lines
1.2 KiB
Python

from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime
from airflow.hooks.http_hook import HttpHook
import json
def send_dingding_alert(context):
print('监测到错误')
task_instance = context.get('task_instance')
url = task_instance.log_url.replace("http://localhost:8080", "https://airflow.fangjia.com")
message = f"[airflow]任务{task_instance.task_id}错误,请点击{url}查看!"
print(message)
http_hook = HttpHook(method="POST", http_conn_id="dingding_webhook")
http_hook.run(
endpoint="robot/send",
data=message.encode('utf-8'),
headers={"Content-Type": "application/json;charset=utf-8"}
)
print("success")
def fail_task():
raise ValueError("This task is designed to fail")
default_args = {
"owner": "airflow",
"retries": 0,
"on_failure_callback": send_dingding_alert, # 任务失败时触发钉钉告警
}
dag = DAG(
'test_failure_notification',
default_args=default_args,
start_date=datetime(2025, 4, 22),
schedule_interval=None
)
task = PythonOperator(
task_id='failing_task',
python_callable=fail_task,
dag=dag
)