具有单一任务的 Apache Airflow DAG

jd2*_*050 7 python airflow

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

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

# ...our DAG's code...
task1 >> task2 >> task3
Run Code Online (Sandbox Code Playgroud)

但如果我的 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?
Run Code Online (Sandbox Code Playgroud)

Nic*_*coE 8

答案是否定的,您不需要包含最后一行。您还可以避免变量的分配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',
    )
Run Code Online (Sandbox Code Playgroud)

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

当开始使用 Airflow 时,我认为使用 DebugExecutor执行这样的快速测试并了解一切是如何工作的非常清晰。如果您使用 VS Code,您可以在此处找到示例配置文件。