先说明一下我使用的airflow 2.2.4版本
-
第一种使用标准构造函数,将dag通过参数传递进去
import pendulum from airflow import DAG from airflow.operators.python import PythonOperator dag = DAG( dag_id='hello_world', start_date=pendulum.datetime(2022, 1, 1), schedule_interval=None, catchup=False, tags=['example'] ) def print_context(): print('---------hello world---------') print_task = PythonOperator(task_id='print_context', python_callable=print_context, dag=dag)
-
第二种,使用隐式的DAG
import pendulum from airflow import DAG from airflow.decorators import task with DAG( dag_id = 'hello_world', start_date=pendulum.datetime(2022, 1, 1), schedule_interval = None, catchup=False, tags=['example'] ) as dag: @task(task_id = 'print_context') def print_context(): print('---------hello world---------') print_task = print_context()
-
第三种,使用装饰器将函数转换成DAG生成器
import pendulum from airflow.decorators import dag, task @dag(dag_id = 'hello_world', start_date=pendulum.datetime(2022, 1, 1), schedule_interval = None, catchup=False, tags=['example'] ) def hello_world2(): @task(task_id = 'print_context') def print_context(): print('---------hello world---------') print_task = print_context() dag = hello_world2()
个人推荐使用第二种方式定义