场景
通过代码生成 Airflow 的 DAG 文件。
具体行为
通过代码生成 python 脚本文件放到指定文件夹。脚本文件内部的代码整体上是差不多的,部分细节可能会差别比较大。
我想到的做法
dag_id = "test_one",
task_id = "bash_task_one",
echo_content = "hello"
func_name = "func_one"
func_content = """
print("world")
"""
content = f'''
from datetime import datetime
from airflow import DAG
from airflow.decorators import task
from airflow.operators.bash import BashOperator
with DAG(dag_id="{dag_id}",
start_date=datetime(2022, 1, 1),
schedule="0 0 * * *") as dag:
hello = BashOperator(task_id="{task_id}", bash_command="echo {echo_content}")
@task()
def {func_name}():
{func_content}
hello >> {func_name}()
'''
with open('/root/dags/test.py', 'w', encoding='utf-8') as fb:
fb.write(content)
把代码放到多行字符串里,然后写到文件中。
想到的问题
- 需要提前把 function 的代码都抽象出来写好,而且不知道缩进会不会有影响
求助
不知道各位大佬们有没有什么好的建议