如何从Python脚本中触发气流DAG运行?

时间:2020-02-04 10:15:24

标签: python python-3.x airflow directed-acyclic-graphs

使用Apache气流,我创建了一些DAGS,其中一些未按计划运行。
我试图找到一种方法,可以从Python脚本中触发特定DAG的运行。这可能吗?我能怎么做?

编辑--- python脚本将在与我所有DAGS所在的项目不同的项目中运行

2 个答案:

答案 0 :(得分:5)

在触发Airflow DAG运行时,您有多种选择。

使用Python

airflow python软件包提供了local client,可用于在python脚本中触发dag。例如:

from airflow.api.client.local_client import Client

c = Client(None, None)
c.trigger_dag(dag_id='test_dag_id', run_id='test_run_id', conf={})

使用Airflow CLI

您可以使用Airflow CLI手动触发气流中断。 here中提供了有关如何使用CLI触发DAG的更多信息。

使用Airflow REST API

您还可以使用Airflow REST API触发DAG运行。有关here的更多信息。


python中的第一个选项可能最适合您(这也是我过去亲自完成的方式)。但是从理论上讲,您可以使用subprocess与python中的CLI进行交互,或者使用requests之类的库与Python中的REST API进行交互。

答案 1 :(得分:0)

在 AWS MWAA Airflow 1.10.12 上,我使用基于 boto3 库的解决方案来处理 Python 和 REST POST 请求:

import boto3
import requests

def TriggerAirflowDAG(mwaa_environment, dag_id):
    client = boto3.client("mwaa")
    token = client.create_cli_token(Name=mwaa_environment)
    url = "https://{0}/aws_mwaa/cli".format(token["WebServerHostname"])
    body = f"trigger_dag {dag_id}"
    headers = {
        "Authorization": "Bearer " + token["CliToken"],
        "Content-Type": "text/plain"
    }
    return requests.post(url, data=body, headers=headers)

启动 DAG 运行的用户/角色必须具有 AmazonMWAAAirflowCliAccess 政策。