SFTP 至 Google Cloud Storage 傳輸運算子¶
Google 提供一項服務 Google Cloud Storage。此服務用於儲存來自各種應用程式的大型資料。SFTP (SSH File Transfer Protocol) 是一種安全的檔案傳輸協定。它透過 SSH 協定運行。它支援 SSH 的完整安全性和驗證功能。
先決條件任務¶
若要使用這些運算子,您必須執行幾項操作
使用 Cloud Console 選擇或建立 Cloud Platform 專案。
啟用您專案的計費功能,如 Google Cloud 文件中所述。
啟用 API,如 Cloud Console 文件中所述。
透過 pip 安裝 API 程式庫。
pip install 'apache-airflow[google]'安裝 提供詳細資訊。
運算子¶
SFTP 和 Google Storage 之間的檔案傳輸是透過 SFTPToGCSOperator
運算子執行。
使用 Jinja 模板與 source_path
、destination_path
、destination_bucket
、impersonation_chain
來動態定義值。
複製單一檔案¶
以下運算子複製單一檔案。
copy_file_from_sftp_to_gcs = SFTPToGCSOperator(
task_id="file-copy-sftp-to-gcs",
source_path=f"{FILE_LOCAL_PATH}/{OBJECT_SRC_1}",
destination_bucket=BUCKET_NAME,
)
移動單一檔案¶
若要移動檔案,請使用 move_object
參數。一旦檔案複製到 Google Storage,SFTP 中的原始檔案將被刪除。destination_path
參數定義儲存桶中檔案的完整路徑。
move_file_from_sftp_to_gcs_destination = SFTPToGCSOperator(
task_id="file-move-sftp-to-gcs-destination",
source_path=f"{FILE_LOCAL_PATH}/{OBJECT_SRC_2}",
destination_bucket=BUCKET_NAME,
destination_path="destination_dir/destination_filename.bin",
move_object=True,
)
複製目錄¶
在 source_path
參數中使用 wildcard
來複製目錄。
copy_directory_from_sftp_to_gcs = SFTPToGCSOperator(
task_id="dir-copy-sftp-to-gcs",
source_path=f"{FILE_LOCAL_PATH}/{SUBDIR}/*",
destination_bucket=BUCKET_NAME,
)
移動特定檔案¶
在 source_path
參數中使用 wildcard
來移動特定檔案。您在路徑中只能使用一個萬用字元。destination_path
定義前綴到所有複製檔案的路徑,例如,tests_sftp_hook_dir/subdir/parent-1.bin
被複製到 specific_files/parent-1.bin
,而 tests_sftp_hook_dir/subdir/parent-2.bin
被複製到 specific_files/parent-2.bin
。tests_sftp_hook_dir/subdir/parent-3.txt
會被略過。
move_specific_files_from_sftp_to_gcs = SFTPToGCSOperator(
task_id="dir-move-specific-files-sftp-to-gcs",
source_path=f"{FILE_LOCAL_PATH}/{SUBDIR}/*.bin",
destination_bucket=BUCKET_NAME,
destination_path="specific_files/",
move_object=True,
)