简体   繁体   English

气流:如何将 xcom 从父 dag 传递到 subdag

[英]Airflow: How to pass xcom from parent dag to subdag

Considering a parent dag that pushes value to xcom, how to retrieve dag from subdag?考虑到将值推送到 xcom 的父 dag,如何从 subdag 中检索 dag?

What I've tried:我试过的:

#parent_dag.py

PARENT_DAG_NAME = "MyParentDag"
CHILD_DAG_NAME = "MyChildDag"

main_dag = DAG(
  dag_id=PARENT_DAG_NAME,
  schedule_interval="@hourly",
  start_date=DAG_START_DATE
)


def push_value(**kwargs):
    ''' push into Xcom '''
    return [1, 2]

t1 = PythonOperator(task_id='push_value',
                       python_callable=push_value,
                       retries=3,
                       dag=main_dag)

subdag_1 = SubDagOperator(
  subdag=Sub_Dag1(
      PARENT_DAG_NAME,
      CHILD_DAG_NAME,
      main_dag.start_date,
      main_dag.schedule_interval,
      "'{{ ti.xcom_pull(task_ids='push_value', dag_id='" + PARENT_DAG_NAME + "' }}'"
  ),
  task_id=CHILD_DAG_NAME,
  dag=main_dag,
)
t1 >> subdag_1

And the child subdag:和孩子 subdag:

#subdag1.py


def use_pushed_val(pushed_val, ds, **kwargs):
    log.info(pushed_val)
    return pushed_val

def Sub_Dag1(parent_dag_name, child_dag_name, start_date, schedule_interval, pushed_val):
  dag = DAG(
    '%s.%s' % (parent_dag_name, child_dag_name),
    schedule_interval=schedule_interval,
    start_date=start_date,
  )

  childTask = PythonOperator(
      task_id='child_task',
      python_callable=use_pushed_val,
      op_kwargs = {'pushed_val' : pushed_val},
      provide_context=True,
      dag=dag
    )

return dag

Instead of child subdag to log and return the [1,2] , it returned string '{{ ti.xcom_pull(task_ids='push_value', dag_id='MyParentDag' }}'它没有使用 child subdag 来记录和返回[1,2] ,而是返回字符串'{{ ti.xcom_pull(task_ids='push_value', dag_id='MyParentDag' }}'

I saw that you've already set the provide_context=True, so that's good.我看到你已经设置了 provide_context=True,所以很好。 This is how i pass variable between parent/child dags using the **context argument.这就是我使用 **context 参数在父/子 dag 之间传递变量的方式。

def push_value(**context):
    context['ti'].xcom_push(key='my_key', value='my_value')

def use_pushed_val(**context):
    value_from_parent = context['ti'].xcom_pull(task_ids=t1.task_id, key='my_key')
{{ti.xcom_pull(task_ids='push_value', dag_id='" + PARENT_DAG_NAME + "')}}

在上面的代码中缺少括号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM