開始使用免費開始

在 Python 中讀取變數

你發現,在 Dags 中使用 Variables 可以在不同環境中提供一些設定的控管,包括你的開發與測試 Airflow 伺服器。為了避免每個環境都要更新 Dag 程式碼,你決定實作一個 Output_Path 變數,用來儲存伺服器上放置各種檔案的位置。

dagtask 物件以及 datetime 已為你匯入。

本練習屬於課程

Python 中的 Apache Airflow 入門

檢視課程

練習說明

  • 匯入用來操作 Variables 所需的函式庫。
  • 從 Airflow 讀取 Output_Path 變數。
  • 若未定義 Output_Path,請提供 /home 作為後備值。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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()
編輯並執行程式碼