简体   繁体   English

Airflow Python Operator - 从 xcom pull 获取参数值

[英]Airflow Python Operator - Get values from xcom pull for params

I have a SQL file like below.我有一个像下面这样的 SQL 文件。

select * from table where data > {{ params.maxdt }}

And Im calling a function from python operator.我从 python 运算符调用函数。 So I need to pass maxdt value while calling that python operator.所以我需要在调用该 python 运算符时传递 maxdt 值。

class SQLTemplatedPythonOperator(PythonOperator):
    template_ext = ('.sql',)

table_list = [public.t1]

for table_name in table_list:
    pull = SQLTemplatedPythonOperator(
    task_id='export_{}'.format(table_name),dag=dag,
    templates_dict={'query': 'public.t1.sql'},
    params = {'table_name': table_name, 'maxdt': {{ti.xcom_pull(task_ids='push_result_{}')}}.format(table_name)},
    op_kwargs={'tablename':table_name},
    python_callable=pgexport,
    provide_context=True,
    )

There was a task called push_result_{}.format(table_name) do some process and push a data value to xcom.有一个名为push_result_{}.format(table_name)执行一些处理并将数据值推送到 xcom。 Now here I need to get that value and pass it inside my pull task.现在,我需要获取该值并将其传递到我的 pull 任务中。 So my SQL templated query will get the value and pass it to the pgexport function.所以我的 SQL 模板查询将获取该值并将其传递给pgexport函数。

pgexport - it will use postgrestogcs operator to push the results of the templated SQL query. pgexport - 它将使用postgrestogcs运算符来推送模板化 SQL 查询的结果。

Unfortunately the syntax I used is not working.不幸的是,我使用的语法不起作用。 Can someone help me to fix this?有人可以帮我解决这个问题吗?

It looks like you've several syntax issues.看起来你有几个语法问题。

The first one is the missing quotation marks around the string, so {{ti.xcom_pull(task_ids='push_result_{}')}}.format(table_name) should become "{{ti.xcom_pull(task_ids='push_result_{}')}}".format(table_name) .第一个是字符串周围缺少引号,所以{{ti.xcom_pull(task_ids='push_result_{}')}}.format(table_name)应该变成"{{ti.xcom_pull(task_ids='push_result_{}')}}".format(table_name)

Now, because you're using the python format function, you've to escape the curly brackets as they're used by the formatter, so you need to change it to:现在,因为您正在使用 python 格式函数,所以您必须在格式化程序使用时对大括号进行转义,因此您需要将其更改为:

"{{{{ ti.xcom_pull(task_ids='push_result_{}') }}}}".format(table_name)

As you can see, curly brackets are escaping themselves, the result after the formatting for table "TABLENAME" would be the following string: {{ ti.xcom_pull(task_ids='push_result_TABLENAME') }} which is now an airflow macro that can be replaced on execution time.如您所见,大括号正在转义,表“TABLENAME”格式化后的结果将是以下字符串: {{ ti.xcom_pull(task_ids='push_result_TABLENAME') }}现在是一个气流宏,可以在执行时替换。

FYI - you can also decide to use the old python formatting to avoid the brackets escaping, something like: "{{ ti.xcom_pull(task_ids='push_result_%s') }}" % "TABLENAME" .仅供参考 - 您也可以决定使用旧的 python 格式来避免括号转义,例如: "{{ ti.xcom_pull(task_ids='push_result_%s') }}" % "TABLENAME"

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

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