具有单一任务的 Apache Airflow DAG

Apache Airflow DAG with single task

我是 Apache Airflow 的新手。 互联网上有很多基本 DAG 的例子。 不幸的是,我没有找到任何单任务 DAG 的例子。

大多数 DAG 示例都在 .py 脚本的末尾包含位移运算符,它定义了任务顺序。 例如:

# ...our DAG's code...
task1 >> task2 >> task3

但是如果我的 DAG 目前只有一个任务怎么办? 我的问题是 - 我是否需要在 Python 文件的末尾使用这个单一任务的名称? 或者如果我们在作用域中只有1个任务,Airflow会自己处理,下面最后一行代码是多余的吗?

from datetime import timedelta
from airflow.operators.bash import BashOperator
from airflow.utils.dates import days_ago

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'email': ['airflow@example.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
}
with DAG(
    'tutorial',
    default_args=default_args,
    description='A simple tutorial DAG',
    schedule_interval=timedelta(days=1),
    start_date=days_ago(2),
    tags=['example'],
) as dag:

    t1 = BashOperator(
        task_id='print_date',
        bash_command='date',
    )

    t1 # IS THIS LINE OF CODE NECESSARY?

答案是否定的,您不需要包括最后一行。您还可以避免变量 t1 的赋值,使 DAG 像这样:

with DAG(
    'tutorial',
    default_args=default_args,
    description='A simple tutorial DAG',
    schedule_interval=timedelta(days=1),
    start_date=days_ago(2),
    tags=['example'],
) as dag:

    BashOperator(
        task_id='print_date',
        bash_command='date',
    )

将运算符实例(例如BashOperator)赋值给变量(在此范围内称为Task)的原因类似于OOP 中的任何其他对象。在您的示例中,没有对 t1 变量执行其他“操作”(您没有读取它或使用它的任何方法)因此没有理由声明它。

当开始使用 Airflow 时,我认为使用 DebugExecutor to perform quick tests like this and understand how everything is working. If you are using VS Code you can find an example config file, here 非常清晰。