要使用Apache Airflow的Web API获取DAG任务的状态,您可以使用Python中的requests库来发送HTTP请求。以下是一个示例代码,演示如何使用Web API获取DAG任务的状态:
import requests
# 设置Airflow Web服务器的URL
airflow_web_url = 'http://localhost:8080'
# 定义要获取状态的DAG任务的ID
dag_id = 'example_dag'
# 定义要获取状态的DAG任务的运行日期
execution_date = '2021-01-01T00:00:00+00:00'
# 构建API的URL
api_url = f'{airflow_web_url}/api/v1/dags/{dag_id}/dagRuns/{execution_date}/'
# 发送GET请求获取任务状态
response = requests.get(api_url)
# 检查响应状态码
if response.status_code == 200:
# 获取任务状态
json_response = response.json()
state = json_response['state']
print(f'The state of DAG {dag_id} on {execution_date} is {state}')
else:
print(f'Failed to get DAG status: {response.text}')
请确保将localhost:8080
替换为您的Airflow Web服务器的实际URL,并将example_dag
替换为您要检查状态的DAG任务的ID。execution_date
应该是DAG任务的实际运行日期。
运行上述代码将发送GET请求到Airflow的Web API,并将任务状态打印到控制台。
注意:在使用此代码之前,请确保您已在Airflow的Web服务器上启用了API,否则此代码将无法正常工作。