Airflow DAGs

Apache Airflow เบื้องต้นด้วย Python

Mike Metzger

Data Engineer

DAG คืออะไร?

DAG หรือ Directed Acyclic Graph:

  • Directed - การไหลระหว่างคอมโพเนนต์แสดงถึงการพึ่งพา
  • Acyclic - ไม่วนลูปหรือทำซ้ำ
  • Graph - ชุดของคอมโพเนนต์

กราฟแบบ Directed Acyclic ที่มีโหนดเชื่อมต่อด้วยลูกศรทิศทางเดียวและไม่มีการวนลูป

Apache Airflow เบื้องต้นด้วย Python

DAG ใน Airflow

  • เขียนด้วย Python (แต่สามารถใช้คอมโพเนนต์จากภาษาอื่นได้)
  • ประกอบด้วย Task ที่ต้องรัน เช่น operators หรือ sensors
  • มีการกำหนด dependencies ทั้งแบบชัดเจนและโดยนัย
    • เช่น คัดลอกไฟล์ไปยังเซิร์ฟเวอร์ก่อนนำเข้าฐานข้อมูล

  Airflow DAG ของ task ที่เชื่อมต่อกันแสดงลำดับการพึ่งพา

Apache Airflow เบื้องต้นด้วย Python

กำหนด 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()
Apache Airflow เบื้องต้นด้วย Python

DAG บน Command Line

 

  • คำสั่ง airflow มี subcommand หลายรายการ
  • airflow -h - แสดงวิธีใช้และคำอธิบาย subcommand

 

  • Subcommand สำหรับ DAG

    • airflow dags list - แสดง DAG ทั้งหมดที่รู้จัก
    • airflow dags reserialize - บังคับให้ Airflow โหลดไฟล์ DAG ใหม่
    • airflow tasks test - รัน task เฉพาะเจาะจง
Apache Airflow เบื้องต้นด้วย Python

Command Line กับ Python

ใช้ command line tool เพื่อ:

  • เริ่มต้นกระบวนการ Airflow
  • รัน DAG / Task ด้วยตนเอง
  • ดูข้อมูล log จาก Airflow

Terminal ที่รัน Airflow command line tool

ใช้ Python เพื่อ:

  • สร้าง DAG
  • แก้ไข properties ของ DAG แต่ละรายการ

ภาพประกอบแสดงโค้ด Python

Apache Airflow เบื้องต้นด้วย Python

มาฝึกกันเถอะ!

Apache Airflow เบื้องต้นด้วย Python

Preparing Video For Download...