開始使用免費開始

為任務加上裝飾器

你決定用 Python 在 Airflow 中實作一個特定任務。這個任務需要在 Airflow 內下載並將檔案儲存到系統,使用 pull_file 函式。此函式已經為你定義好了。

requests 函式庫以及 Airflow 的 dag 物件都已替你匯入。

本練習屬於課程

Python 中的 Apache Airflow 入門

檢視課程

練習說明

  • 從 Airflow 函式庫匯入所需的物件。
  • pull_file 函式設定為一個 Airflow 任務。
  • 呼叫該任務物件。

動手互動練習

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

# Import the task decorator
from ____ import ____

@dag(dag_id='file_update')
def file_update():
  # Decorate the function as a task
  ____
  def pull_file(URL, savepath):
    r = requests.get(URL)
    with open(savepath, 'wb') as f:
      f.write(r.content)   
    print(f"File pulled from {URL} and saved to {savepath}")
  # Call the task
  ____('http://dataserver/sales.json', 'latestsales.json')

file_update()
編輯並執行程式碼