การอ่านตัวแปรใน Python
การใช้ Variables ภายใน DAG จะช่วยให้ควบคุมการตั้งค่าในแต่ละสภาพแวดล้อมได้ ไม่ว่าจะเป็นเซิร์ฟเวอร์ Airflow สำหรับการพัฒนาหรือการทดสอบ เพื่อไม่ต้องแก้โค้ด DAG ทุกครั้ง จึงตัดสินใจสร้างตัวแปร Output_Path เพื่อเก็บตำแหน่งบนเซิร์ฟเวอร์ที่ใช้จัดเก็บไฟล์ต่าง ๆ
ออบเจ็กต์ dag และ task ถูก import ไว้ให้แล้ว พร้อมกับ datetime
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Apache Airflow เบื้องต้นด้วย Python
คำแนะนำการฝึกหัด
- Import ไลบรารีที่จำเป็นสำหรับการทำงานกับ Variables
- อ่านตัวแปร
Output_Pathจาก Airflow - กำหนดค่าสำรองเป็น
/homeหากยังไม่ได้กำหนดOutput_Pathไว้
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import the proper library to read Variables
from airflow.____ import ____
@dag(dag_id='process_sales', start_date=datetime(2026, 4, 15))
def process_sales():
@task()
def parse_file():
# Get the output file location, otherwise default to "/home"
output_path = ____.____("Output_Path", ____="/home")
# Logging only currently - processing to be added later
print(f"File parsed and saved to {output_path}/sales_report.pdf")
parse_file()
process_sales()