[英]How to make a DAG in Apache Airflow run like a simple cron job?
[英]How make branches in a Apache Airflow Dag?
我有一个这样的 dag(这是一个半伪代码),我想根据他们的 output 在不同的分支中执行任务。
#This is a method that return a or b
def dosth():
.....
return a or b
t1 = PythonOperator(
't1',
python_callable = dosth
)
branchA = BashOperator(
'branchA',....
)
branchB = BashOperator(
'branchB',....
)
我想要的是如果dosth
返回a,我希望dag执行branchA中的任务,如果它返回b,我希望dag执行branchB中的任务。 任何人都知道我们该如何解决这个问题?
检查有关分支的文档: https://airflow.apache.org/docs/stable/concepts.html?highlight=branch#branch
您需要使用BranchPythonOperator
,您可以在其中指定要评估的条件,以决定接下来应该运行哪个任务。
基于您的半伪代码的示例:
def dosth():
if some_condition:
return 'branchA'
else:
return 'branchB'
t1 = BranchPythonOperator(
task_id='t1',
provide_context=True,
python_callable= dosth,
dag=dag)
branchA = BashOperator(
'branchA',....
)
branchB = BashOperator(
'branchB',....
)
您传递给python_callable
应该返回应该运行的下一个任务的task_id
。
另一个例子:
def branch_func(**kwargs):
ti = kwargs['ti']
xcom_value = int(ti.xcom_pull(task_ids='start_task'))
if xcom_value >= 5:
return 'continue_task'
else:
return 'stop_task'
start_op = BashOperator(
task_id='start_task',
bash_command="echo 5",
xcom_push=True,
dag=dag)
branch_op = BranchPythonOperator(
task_id='branch_task',
provide_context=True,
python_callable=branch_func,
dag=dag)
continue_op = DummyOperator(task_id='continue_task', dag=dag)
stop_op = DummyOperator(task_id='stop_task', dag=dag)
start_op >> branch_op >> [continue_op, stop_op]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.