如何在Airflow DAG中获取REST API的Host并生成URL发送邮件?
Airflow DAG中获取API访问URL并发送邮件的实现方式
你可以通过以下几种方式获取Airflow API的公网访问URL,无需手动硬编码host参数:
方法1:直接读取Airflow配置
Airflow的airflow.cfg中core.web_server_url配置项存储了Web UI的公网地址,API路径基于该地址构建。你可以通过conf对象直接读取这个配置:
from airflow.configuration import conf from airflow.operators.email import EmailOperator # 从配置中获取公网访问地址 AIRFLOW_PUBLIC_URL = conf.get("core", "web_server_url") # 当前DAG的ID,也可以直接用dag.dag_id(如果在DAG定义内) TARGET_DAG_ID = "your_target_dag_id" RECIPIENT = "指定收件人邮箱" SUBJECT = "DAG API访问链接" send_email_task = EmailOperator( task_id="send_email", to=RECIPIENT, subject=SUBJECT, html_content=f"""<body>你可以通过以下链接触发DAG:{AIRFLOW_PUBLIC_URL}/api/v1/dags/{TARGET_DAG_ID}/</body>""" )
方法2:使用Airflow模板上下文(更灵活)
EmailOperator默认支持Airflow模板语法,你可以直接在html_content中引用模板变量,自动获取当前DAG的ID和Web服务地址:
from airflow.operators.email import EmailOperator RECIPIENT = "指定收件人邮箱" SUBJECT = "DAG API访问链接" send_email_task = EmailOperator( task_id="send_email", to=RECIPIENT, subject=SUBJECT, html_content="""<body>你可以通过以下链接触发DAG:{{ conf.core.web_server_url }}/api/v1/dags/{{ dag.dag_id }}/</body>""" )
关键注意事项
- 确保
airflow.cfg中的web_server_url配置的是公网可访问的完整地址(例如https://your-airflow-public-domain.com),而非内网或localhost地址 - 模板方式中,
dag.dag_id会自动获取当前DAG的ID,无需手动指定,适合复用性高的场景 - 如果需要动态修改地址,也可以将公网地址存入Airflow Variables,用
{{ var.value.airflow_public_url }}引用
内容的提问来源于stack exchange,提问作者Justin
相关产品推荐
相关产品推荐

