Airflow Dag

Python 中的 Apache Airflow 入门

Mike Metzger

Data Engineer

什么是 Dag?

Dag,即有向无环图(Directed Acyclic Graph):

  • 有向:组件间的数据流表示依赖关系
  • 无环:不出现循环或重复
  • 图:组件的集合

有向无环图,节点以单向箭头相连且无循环

Python 中的 Apache Airflow 入门

Airflow 中的 Dag

  • 用 Python 编写(可调用其他语言实现的组件)
  • 由要执行的任务构成,如 operators 或 sensors
  • 包含显式或隐式的依赖
    • 例如:先将文件复制到服务器,再导入到数据库服务。

  Airflow Dag 的任务连接图,展示依赖顺序

Python 中的 Apache Airflow 入门

定义 Dag

Dag 示例(Taskflow API):

from airflow.sdk import dag

from pendulum import datetime @dag( dag_id='etl_workflow', email='[email protected]', start_date=datetime(2026, 3, 15, tz="UTC") )
def etl_workflow(): ...
etl_workflow()
Python 中的 Apache Airflow 入门

命令行中的 Dags

 

  • airflow 命令行包含许多子命令
  • airflow -h:查看帮助和子命令说明

 

  • Dag 相关子命令

    • airflow dags list:显示所有已识别的 Dag
    • airflow dags reserialize:强制 Airflow 重新加载 Dag 文件
    • airflow tasks test:运行指定任务
Python 中的 Apache Airflow 入门

命令行 vs Python

使用命令行工具可:

  • 启动 Airflow 进程
  • 手动运行 Dags / Tasks
  • 获取 Airflow 的日志信息

终端运行 airflow 命令行工具

使用 Python 可:

  • 创建 Dag
  • 编辑 Dag 的各项属性

表示 Python 代码的插图

Python 中的 Apache Airflow 入门

Passons à la pratique !

Python 中的 Apache Airflow 入门

Preparing Video For Download...