Python 如何在json模板中传递ts_nodash
我需要一个来自Ariflow dag的API调用 下面是我在代码中使用的json_字符串示例:Python 如何在json模板中传递ts_nodash,python,json,google-cloud-platform,airflow,airflow-api,Python,Json,Google Cloud Platform,Airflow,Airflow Api,我需要一个来自Ariflow dag的API调用 下面是我在代码中使用的json_字符串示例: def api_call_func(**context): source_file_name = context["dag_run"].conf["source_file_names"] json_data = { "filenames":[ {"FileName&q
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>
f'Source\u credit{{ts\u nodash}
以下是currentDateTime所需的响应:
<filenames>
<FileName>f'Source_credit_20210408010223</FileName>
</filenames>
f'Source_credit_20210408010223
如何在json中传递ts_nodash宏?
或者如何在json中传递dag的执行日期时间?仅当包含模板的字符串作为参数传递给运算符的模板参数时,才会处理模板。例如,
op_args
PythonOperator的参数
在您的例子中,ts\u nodash
的值作为参数由PythonOperator
传递给api\u call\u func()
。因此,您可以使用上下文
参数访问它:
json_data = {
"ID": "A001-001",
"SourceName": sourcefile,
"filenames": [{"FileName": [f"Source_credit_{context['ts_nodash']}"]}],
}
注意,其余部分的值可以用相同的方式访问。只有当包含模板的字符串作为参数传递给运算符的模板参数时,才会处理模板。例如,
op_args
PythonOperator的参数
在您的例子中,ts\u nodash
的值作为参数由PythonOperator
传递给api\u call\u func()
。因此,您可以使用上下文
参数访问它:
json_data = {
"ID": "A001-001",
"SourceName": sourcefile,
"filenames": [{"FileName": [f"Source_credit_{context['ts_nodash']}"]}],
}
注意,其余部分的值可以用相同的方式访问。您如何确切地使用
json\u str
?仅当包含模板的字符串作为参数传递给运算符的模板参数时,才会处理模板。例如,PythonOperator
的op_args
参数。如前所述,它定义了哪些参数可以模板化或不模板化,这在很大程度上取决于特定的操作员实现。你能和我们分享一些代码行吗?请找到添加的代码行。希望它能帮助@Nick_KhI添加代码行,展示如何使用json_str。请帮助@Sergiykolesnikov你到底是如何使用json\u str
?仅当包含模板的字符串作为参数传递给运算符的模板参数时,才会处理模板。例如,PythonOperator
的op_args
参数。如前所述,它定义了哪些参数可以模板化或不模板化,这在很大程度上取决于特定的操作员实现。你能和我们分享一些代码行吗?请找到添加的代码行。希望它能帮助@Nick_KhI添加代码行,展示如何使用json_str。请帮助@SergiyKolesnikovI也可以做-json_data={“ID”:“A001-001”,“SourceName”:sourcefile,“FileName”:[{“FileName”:[f”Source_credit{context['execution_date.subtract(seconds=2).strftime(“%Y%m%d%H%m%S”)]},}
@SergiyKolesnikovI不这么认为,但你可以得到cotext['execution date
然后将其转换为日期时间并进一步处理。{context[“execution_date”].subtract(seconds=2).strftime(“%Y%m%d%H%m%S”)}
这一个有效。非常感谢:)@SergiyKolesnikovI也可以做-json_data={“ID”:“A001-001”,“SourceName”:sourcefile,“FileName”:[{“FileName”:[f”Source_credit{context['execution_date.subtract(seconds=2).strftime(“%Y%m%d%H%m%S”)]}},}
@SergiyKolesnikovI不这么认为,但你可以得到cotext['execution date
然后将其转换为日期时间并进一步处理。{context[“execution_date”].subtract(seconds=2).strftime(“%Y%m%d%H%m%S”)}
这一个有效。非常感谢:)@SergiyKolesnikov