在 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()