访问气流中的 'ds' 变量

Accessing the 'ds' variable in airflow

我可以访问 python 代码中的宏,如下所示:

partition_dt = macros.ds_add(ds, 1)

但我无法弄清楚如何获取似乎只能在模板中访问的 ds 变量本身。有什么指点吗?

我假设您想调用内置 AirFlow ds 的默认变量之一 - 执行日期为 YYYY-MM-DD

要仅调用 ds,您可以这样做:

EXEC_DATE = '{{ ds }}'

调用你想要的 - macros.ds_add:

EXEC_DATE = '{{ macros.ds_add(ds, 1) }}'

并以这种方式加载它:

T1 = BashOperator(\
        task_id='test_ds',
        bash_command='echo ' + EXEC_DATE
        dag=DAG)

如果你想格式化它(就像我不得不做的那样),你可以这样做:

EXEC_DATE = '{{ macros.ds_format(macros.ds_add(ds, 1), "%Y-%m-%d", "%Y%m%d") }}'

简短回答,ds 和宏变量只能通过模板访问,因为它们仅在执行期间存在,而不是在 python 代码解析期间(当 dag 由气流加载时)。

这个问题与这个问题非常相似: and I try to explain the difference between the 2 steps and how to have the execution date in a variable in the last answer :