Airflow实战–获取Rest参数并通过Variable传递给Bash算子
本文介绍如何通过REST API把参数传递给DAG。在DAG内部,如何在Task之间进行参数传递。前面介绍了,如何通过xcom来在dag中不同任务重传递参数,这里介绍如何通过共享变量的方式在各个task之间传递参数。
获取Rest参数并通过Variable传递
以下任务先通过PythonOperator获取到Rest接口的参数,并通过Variable共享变量的方式来把参数传递给后面的任务。而且,这里后面的任务是BashOperator类型的算子。
这里要注意,在BashOperator中获取共享变量的值的范式是:{{ var.value.pass_key2 }}
。其中var.value是表示获取共享变量的值,后面的pass_key2是前序任务设置的共享变量的key的名称。
实际的代码如下:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
import airflow
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from datetime import timedelta
from airflow.models import Variable
default_args = {
'owner': 'user1',
'depends_on_past': False,
'start_date': airflow.utils.dates.days_ago(1),
'email': ['user1@qq.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=3),
}
dag = DAG(
'rest_pass_methods',
default_args=default_args,
description='test method to get rest paramaters.',
schedule_interval=timedelta(days=1))
# 在bash中获取共享变量参数的值
bash_print_param="echo \"Last print param:[{{ var.value.pass_key2 }}]\""
third_operator = BashOperator(
task_id='third_task',
bash_command=bash_print_param,
dag=dag)
def use_param(**context):
print("second task: ")
print("pass_key is :" + Variable.get("pass_key"))
pass_value = "%s_2" % Variable.get("pass_key")
Variable.set("pass_key2", pass_value)
# return "second_task ret value"
second_operator = PythonOperator(
task_id='second_task',
python_callable=use_param,
dag=dag)
# 接收REST API的参数
def receive_param(**context):
# 获取key为push_key的rest接口参数
stock_list = context["dag_run"].conf.get("push_key")
print("returned tickers: %s" % str(stock_list))
Variable.set("pass_key", stock_list)
# return "first_task ret value"
first_operator = PythonOperator(
task_id='first_task',
python_callable=receive_param,
dag=dag)
second_operator.set_upstream(first_operator)
third_operator.set_upstream(second_operator)
触发DAG执行的REST请求
下面是启动DAG的shell命令:
EXE_DATE=$(TZ=America/Curacao date '+%Y-%m-%dT%H:%M:%SZ')
curl -X POST 'http://localhost:20001/api/v1/dags/rest_pass_methods/dagRuns' \
-d "{\"execution_date\": \"${EXE_DATE}\", \"conf\": {\"push_key\":\"use db1; show tables;\"}}" \
-H 'content-type: application/json' \
--user "user1:user1"
注意:可以通过任意能够发送post请求的工具来发送以上命令,比如postman等等。
小结
本文通过实际的例子说明了如何获取REST接口的参数,并通过Airflow的Variable共享变量,来把参数传递给了不同类型的算子,这里是把Python算子设置的Variable值传递给了Bash类型的算子。
这样,就可以通过REST接口在不同类型之间的任务传递参数,从而让参数在整个DAG的各个任务之间传递。