使用Python的字符串格式化来操作
可以使用Python字符串的.format()方法来格式化字符串,以替代在Airflow中使用Jinja模板引擎中的{{run_id}}。下面是一个示例:
from airflow import DAG from datetime import datetime from airflow.operators.python_operator import PythonOperator
def my_function(ds, **kwargs): run_id = kwargs.get('run_id') my_string = 'This is my string with run_id {}'.format(run_id) print(my_string)
with DAG('my_dag', start_date=datetime(2021, 1, 1)) as dag: my_task = PythonOperator( task_id='my_task', provide_context=True, python_callable=my_function )
在这个例子中,my_function()函数接收两个参数,ds和kwargs。kwargs包含所有上下文变量,包括run_id。在函数中,通过kwargs.get('run_id')从kwargs中获取run_id的值,并使用字符串格式化将其插入到字符串中。最后,my_string被打印出来,在控制台中显示出来。
可以通过使用这种方法替代使用Jinja模板引擎来轻松地操作字符串,而不会遇到任何问题。