始める無料で始める

Python で変数を読み取る

DAG 内で Variables を活用すると、開発環境やテスト用の Airflow サーバーなど、さまざまな環境での設定を柔軟に管理できることに気づきました。そこで、各環境ごとに DAG のコードを書き換えなくて済むよう、サーバー上のファイル保存先パスを管理する Output_Path 変数を実装することにしました。

dag オブジェクトと task オブジェクトは 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()
コードを編集して実行