python - 将宏值传递给气流中的sql文件
问题描述
我有一个 sql 文件,有一个 sql 查询:-
delete from xyz where id in = 3 and time = '{{ execution_date.subtract(hours=2).strftime("%Y-%m-%d %H:%M:%S") }}';
在这里,我在 sql 查询本身中编写宏,我想从操作员调用此 sql 查询的 python 文件中传递它的值。
time = f'\'{{{{ execution_date.subtract(hours= {value1}).strftime("%Y-%m-%d %H:%M:%S") }}}}\''
我想将此全局时间变量传递给 sql 文件,而不是再次在那里编写完整的宏。
PostgresOperator(dag=dag,
task_id='delete_entries',
postgres_conn_id='database_connection',
sql='sql/delete_entry.sql')
如果我time
在查询中使用 jinja 模板 as {{ time }}
,而不是评估它,它只作为一个完整的字符串传递。请帮助,坚持了很长时间。
解决方案
由于您想f'\'{{{{ execution_date.subtract(hours= {value1}).strftime("%Y-%m-%d %H:%M:%S") }}}}\''
在不复制代码的情况下使用两个运算符,您可以将其定义为用户宏。
from datetime import datetime
from airflow import DAG
from airflow.providers.postgres.operators.postgres import PostgresOperator
def ds_macro_format(execution_date, hours):
return execution_date.subtract(hours=hours).strftime("%Y-%m-%d %H:%M:%S")
user_macros = {
'format': ds_macro_format
}
default_args = {
'owner': 'airflow',
'start_date': datetime(2021, 6, 7),
}
dag = DAG(
"stackoverflow_question1",
default_args=default_args,
schedule_interval="@daily",
user_defined_macros=user_macros
)
PostgresOperator(dag=dag,
task_id='delete_entries',
postgres_conn_id='database_connection',
sql='sql/delete_entry.sql')
和delete_entry.sql
作为:
delete from xyz where id in = 3 and time = {{ format(execution_date, hours=2) }};
假设您还想在 BashOperator 中使用宏,您可以这样做:
BashOperator(
task_id='bash_task',
bash_command='echo {{ format(execution_date, hours=2) }} ',
dag=dag,
)
推荐阅读
- php - 通过连接表获取不同数组中的结果
- google-cloud-platform - 代码:EXTERNAL_RESOURCE_NOT_FOUND;消息:资源'
-compute@developer.gserviceaccount.com' 类型为 'serviceAccount' 未找到 - flutter - StreamBuilder 完全加载后有没有办法获得回调?
- amazon-web-services - 当节点数超过一个时,Redislabs UI 日志记录错误
- asp.net-core - 网络核心中的数据注释不适用于列表
- javascript - Nodemails 给我 TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。接收类型未定义
- python - 在此类查询中查找或聚合
- grub - 创建一个自动检测 EFI 系统并启动第一个系统的 grub 脚本
- api - 如何使用 Vtiger API 在修改时间上查询模块(潜力)
- python - 英特尔实感 - 在两个 numpy 数组中对齐深度和颜色