【发布时间】:2019-03-01 12:41:33
【问题描述】:
我需要每天将文件从 FTP 上传到 Google Cloud Storage。我已经设法通过从 FTP 下载文件并上传到 Google Cloud Storage 来使用 Python,但它似乎太重了。所以,我很好奇是否可以通过在 Google Cloud Shell 中执行命令来实现它,或者是否有任何其他可能的解决方案可以以更优化的方式实现它。
from gcloud import storage
from oauth2client.service_account import ServiceAccountCredentials
import os
ftp = ftplib.FTP("ftp_url")
ftp.login('login', 'password')
ftp.cwd("/")
with open('file', 'wb') as f:
ftp.retrbinary('RETR ' + 'file', f.write)
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
credentials_dict
)
client = storage.Client(credentials=credentials, project='project_id')
bucket = client.get_bucket('bucket')
blob = bucket.blob('file')
blob.upload_from_filename('file')
【问题讨论】:
-
除了没有错误处理和使用
from_json_keyfile_dict之外,你的代码都很好。您使从 FTP 服务器下载文件和上传 GCS 变得简单。我会为 FTP 文件传输模式添加一个有意的二进制设置。
标签: python python-2.7 google-cloud-platform ftp google-cloud-storage