将文件从 URL 传输到 Cloud Storage

Rao*_*oot 3 python google-cloud-storage google-cloud-platform google-cloud-functions

我是一名 Ruby 开发人员,尝试使用 Python 编写的 Google Cloud Functions,但在将远程文件从给定 URL 传输到 Google Cloud Storage (GCS) 时遇到了困难。

在等效的 RoR 应用程序中,我下载到应用程序的临时存储,然后上传到 GSC。

我希望有一种方法可以通过云功能简单地将远程文件“下载”到我的 GCS 存储桶中。

这是我对一些注释所做的简化示例,真正的代码从私有 API 获取 URL,但这工作正常并且不是问题所在。

from google.cloud import storage
project_id = 'my-project'
bucket_name = 'my-bucket'
destination_blob_name = 'upload.test'
storage_client = storage.Client.from_service_account_json('my_creds.json')

# This works fine
#source_file_name = 'localfile.txt'

# When using a remote URL I get 'IOError: [Errno 2] No such file or directory'
source_file_name = 'http://www.hospiceofmontezuma.org/wp-content/uploads/2017/10/confused-man.jpg'

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_filename(source_file_name)

upload_blob(bucket_name, source_file_name, destination_blob_name)
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Joa*_*oël 11

无法直接从 URL 将文件上传到 Google Cloud Storage。由于您是从本地环境运行脚本,因此要上传的文件内容需要位于同一环境中。这意味着 url 的内容需要存储在内存中或文件中。

基于您的代码显示如何执行此操作的示例:

选项 1:您可以使用该wget模块,它将获取 url 并将其内容下载到本地文件中(类似于wgetCLI 命令)。请注意,这意味着该文件将存储在本地,然后从该文件上传。我添加了os.remove一行以在上传完成后删除文件。

from google.cloud import storage
import wget
import io, os

project_id = 'my-project'
bucket_name = 'my-bucket'
destination_blob_name = 'upload.test'
storage_client = storage.Client.from_service_account_json('my_creds.json')

source_file_name = 'http://www.hospiceofmontezuma.org/wp-content/uploads/2017/10/confused-man.jpg'

def upload_blob(bucket_name, source_file_name, destination_blob_name):   
    filename = wget.download(source_file_name)

    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_filename(filename, content_type='image/jpg')
    os.remove(filename)

upload_blob(bucket_name, source_file_name, destination_blob_name)
Run Code Online (Sandbox Code Playgroud)

选项 2:使用urllib模块,其工作方式与模块类似wget,但不是写入文件,而是写入变量。请注意,我在 Python3 中完成了此示例,如果您计划在 Python 2.X 中运行脚本,则存在一些差异。

from google.cloud import storage
import urllib.request

project_id = 'my-project'
bucket_name = 'my-bucket'
destination_blob_name = 'upload.test'
storage_client = storage.Client.from_service_account_json('my_creds.json')

source_file_name = 'http://www.hospiceofmontezuma.org/wp-content/uploads/2017/10/confused-man.jpg'

def upload_blob(bucket_name, source_file_name, destination_blob_name):   
    file = urllib.request.urlopen(source_file_name)

    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_string(link.read(), content_type='image/jpg')

upload_blob(bucket_name, source_file_name, destination_blob_name)
Run Code Online (Sandbox Code Playgroud)