【问题标题】:how to pass airflow ts_nodash in a json template如何在 json 模板中传递气流 ts_nodash
【发布时间】:2021-07-04 05:49:50
【问题描述】:

我需要从 Ariflow dag 调用 API。

以下是我在代码中使用的示例 json_string:

    def api_call_func(**context):
        source_file_name = context["dag_run"].conf["source_file_names"]
    json_data = { "filenames":[
                 {"FileName":[f'Source_credit_{{{{ ts_nodash }}}}']}
                  ]
                }

        json_string = json.dumps(json_data, 
                        skipkeys = True, 
                        allow_nan = True)
        requests.post(url = API_URL, data = json_string)

    api_task = PythonOperator(
    task_id='api_task',
    provide_context=True,
    python_callable=api_call_func,
    dag=dag,
    )

但它会导致以下响应:

<filenames>
         <FileName>f'Source_credit_{{ ts_nodash }}</FileName>
</filenames>

以下是 currentDateTime 所需的响应:

<filenames>
         <FileName>f'Source_credit_20210408010223</FileName> 
</filenames>

如何在 json 中传递 ts_nodash 宏? 或者如何在 json 中传递 dag 的执行日期时间?

【问题讨论】:

  • 你到底是如何使用json_str的?仅当包含模板的字符串作为参数传递给运算符的模板化参数时,才会处理模板。例如,PythonOperatorop_args 参数。
  • 如前所述,Airflow 定义了哪些参数可以模板化或不模板化,它在很大程度上取决于特定的运营商实现。您能否与我们分享一些代码行以正确理解这一点?
  • 请找到添加的代码行。希望它可以帮助@Nick_Kh
  • 我添加了代码行,显示了如何使用 json_str。请帮助@SergiyKolesnikov

标签: python json google-cloud-platform airflow airflow-api


【解决方案1】:

仅当包含模板的字符串作为参数传递给运算符的模板化参数时,才会处理模板。例如,op_argsPythonOperator 的参数。

在您的情况下,ts_nodash 的值作为PythonOperator 的参数传递给api_call_func()。因此,您可以使用context 参数来访问它:

json_data = {
    "ID": "A001-001",
    "SourceName": sourcefile,
    "filenames": [{"FileName": [f"Source_credit_{context['ts_nodash']}"]}],
}

注意,default variables 其余部分的值可以通过相同方式访问。

【讨论】:

  • 我也可以吗 - json_data = { "ID": "A001-001", "SourceName": sourcefile, "filenames": [{"FileName": [f"Source_credit_{ context['execution_date.subtract(seconds=2).strftime("%Y%m%d%H%M%S")'] }"]}], } @SergiyKolesnikov
  • 我不这么认为,但你可以得到cotext['execution_date'] 然后将其转换为日期时间并进一步处理。
  • { context["execution_date"].subtract(seconds=2).strftime("%Y%m%d%H%M%S") } 这个有效。非常感谢 :) @SergiyKolesnikov
猜你喜欢
  • 2021-07-16
  • 2014-08-22
  • 2020-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-16
  • 1970-01-01
  • 2020-05-02
相关资源
最近更新 更多