简体   繁体   English

无法在 Airflow 中的自定义运算符中通过 xcom

[英]Unable to pass xcom in Custom Operators in Airflow

I have a simple, linear DAG(created using Airflow 2.0) with two tasks.我有一个简单的线性 DAG(使用 Airflow 2.0 创建)有两个任务。 I have custom operators for each of the task which extend over BaseOperator .我为扩展BaseOperator的每个任务都有自定义运算符。 Following is the code for dag and operators:-以下是 dag 和操作符的代码:-

class Operator1(BaseOperator):
    @apply_defaults
    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)
    def execute(self, context):
        ...
        logging.info('First task')
        context['task_instance'].xcom_push(key="payload", value=data)
        return data

class Operator2(BaseOperator):
    @apply_defaults
    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)
    def execute(self, context):
        ...
        logging.info("context is ", context)
        parameters = context['task_instance'].xcom_pull(key="payload", value=data)
 

with DAG('dag_1', default_args=DEFAULT_ARGS, schedule_interval=None) as dag:
    TASK_1 = Operator1(
        task_id='task_1',
        do_xcom_push=True)
    TASK_2 = Operator2(
        task_id='task_2',
        do_xcom_push=True)
    TASK_1 >> TASK_2 

When I run the DAG, I find that context which is used for getting xcom values is empty.当我运行 DAG 时,我发现用于获取xcom值的context是空的。 I have searched a lot of answers on stackoverflow and tried the way mentioned in them but they didn't work.我在stackoverflow上搜索了很多答案,并尝试了其中提到的方式,但没有奏效。

Would really appreciate some hint over the issue - how to push and pull xcom values in custom operators?真的很感激这个问题的一些提示 - 如何在自定义运算符中推送和拉取 xcom 值?

I took your code and run it, the first problem was that start_date wasn't defined, so it ended up in an exception:我拿了你的代码并运行它,第一个问题是start_date没有定义,所以它最终出现了一个异常:

Exception has occurred: AirflowException (note: full exception trace is shown but execution is paused at: _run_module_as_main)
Task is missing the start_date parameter

Also, in Operator1 class, data variable is not defined.此外,在Operator1 class 中,未定义data变量。 I guess maybe you missed them when you made the code example.我想也许你在制作代码示例时错过了它们。

Other than that the code worked, but I think you should consider defining the task_id parameter when doing the xcom_pull operation.除了代码有效之外,我认为您应该在执行 xcom_pull 操作时考虑定义task_id参数。

From TaskInstance xcom_pull method description:来自TaskInstance xcom_pull方法描述:

:param task_ids: Only XComs from tasks with matching ids will be pulled. :param task_ids:只有具有匹配 id 的任务中的 XCom 才会被拉取。 Can pass None to remove the filter.可以通过 None 来删除过滤器。

Here is the code of a working example, note that I use two equivalent methods to perform the XComs operations:这是一个工作示例的代码,请注意,我使用两种等效方法来执行XComs操作:

from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.utils.decorators import apply_defaults
from airflow.models import BaseOperator


class Operator1(BaseOperator):
    @apply_defaults
    def __init__(self,  *args, **kwargs) -> None:
        super(Operator1, self).__init__(*args, **kwargs)

    def execute(self, context):
        print('First task')
        data = "valuable_data"
        more_data = "more_valueable_data"
        context['task_instance'].xcom_push(key="payload", value=data)
        self.xcom_push(context, "more_data", more_data)
        return data


class Operator2(BaseOperator):
    @apply_defaults
    def __init__(self,  *args, **kwargs) -> None:
        super(Operator2, self).__init__(*args, **kwargs)

    def execute(self, context):
        # print(f"context is  {context}")
        data = context['task_instance'].xcom_pull(
            "task_1",
            key="payload")
        more_data = self.xcom_pull(context, "task_1", key="more_data")

        print(f"Obtained data: {data}")
        print(f"Obtained more_data: {more_data}")


with DAG('dag_1',
         default_args={'owner': 'airflow'},
         start_date=days_ago(1),
         catchup=False,
         schedule_interval=None) as dag:

    TASK_1 = Operator1(
        task_id='task_1'
    )
    TASK_2 = Operator2(
        task_id='task_2'
    )
    TASK_1 >> TASK_2

Log from Task_2:来自 Task_2 的日志:

[2021-06-15 12:55:01,206] {taskinstance.py:1255} INFO - Exporting the following env vars:
AIRFLOW_CTX_DAG_OWNER=airflow
AIRFLOW_CTX_DAG_ID=dag_1
AIRFLOW_CTX_TASK_ID=task_2
AIRFLOW_CTX_EXECUTION_DATE=2021-06-14T00:00:00+00:00
AIRFLOW_CTX_DAG_RUN_ID=backfill__2021-06-14T00:00:00+00:00
Obtained data: valuable_data
Obtained more_data: more_valueable_data
[2021-06-15 12:55:01,227] {taskinstance.py:1159} INFO - Marking task as SUCCESS. dag_id=dag_1, task_id=task_2, execution_date=20210614T000000, start_date=20210615T120402, end_date=20210615T125501

Side notes: I changed the __init__ method in order to accept *args as well.旁注:我更改了__init__方法以便也接受 *args。 I'm using print but It could be done using Airflow logger as self.log.info('msg') .我正在使用print ,但可以使用 Airflow 记录器作为self.log.info('msg')来完成。

Let me know if that worked for you!让我知道这是否对您有用!

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

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