Airflow 感測器

Python 中的 Apache Airflow 入門

Mike Metzger

Data Engineer

感測器

  • 等待條件為真的作業元件
    • 建立檔案
    • 上傳資料庫記錄
    • 網路請求回應
  • 可設定檢查條件為真的頻率
  • 指派給工作

Airflow 感測器等待條件變為真的示意圖

Python 中的 Apache Airflow 入門

感測器細節

  • 繼承自 airflow.sdk.BaseSensorOperator
  • 感測器參數:
  • mode-如何檢查條件
    • mode='poke'-預設,重複執行
    • mode='reschedule'-釋出工作槽位,稍後再試
  • poke_interval-兩次檢查間隔
  • timeout-逾時後標記工作失敗
  • 也包含一般作業元件屬性
Python 中的 Apache Airflow 入門

檔案感測器

  • 屬於 airflow.providers.standard.sensors 函式庫
  • 檢查指定位置是否存在檔案
  • 也可檢查目錄中是否有任何檔案
from airflow.providers.standard.sensors.filesystem import FileSensor

file_sensor_task = FileSensor(task_id='file_sense',
                              filepath='salesdata.csv',
                              poke_interval=300,
                              timeout=3000
                              )

init_sales_cleanup() >> file_sensor_task >> generate_report()
Python 中的 Apache Airflow 入門

其他感測器

  • airflow.providers.*.sensors 中還有許多
  • ExternalTaskSensor-等待另一個 Dag 的工作完成
  • HttpSensor-發送網頁 URL 請求並檢查內容
  • SqlSensor-執行 SQL 查詢以檢查內容
Python 中的 Apache Airflow 入門

何時使用感測器?

  • 何時條件會為真不確定
  • 不希望立刻失敗
  • 在不寫迴圈下重複嘗試

 

 

Airflow 感測器等待條件變為真的示意圖

Python 中的 Apache Airflow 入門

一起來練習吧!

Python 中的 Apache Airflow 入門

Preparing Video For Download...