Python url 将文件检索到 Google 云存储

Python urlretrieve a file to Google Cloud Storage

我正在尝试在 GAE 上部署应用程序。
我的 python 脚本使用 urllib.request 包中的 urlretrieve 函数下载图像:

urlretrieve(img_url,os.path.join(os.getcwd(),img_dir,str(img_name) + '.jpg'))

它工作正常,只要我是 运行 本地脚本(在本地保存图像),但我无法找到替代方法来使用 GCS 执行相同操作。

如果有人能指出我如何实现这一点,我将不胜感激。

谢谢!

documentation 展示了如何使用一些简单的方法来读取和写入 Cloud Storage 存储桶。

而不是 urlretrieve,只需获取图像的内容,然后将响应写入云存储中的文件。

image_binary = urllib.urlopen(img_url).read()

假设您将 Cloud Storage 示例稍微修改为:

import cloudstorage as gcs

def create_file(self, filename, contents, mime_type='image/jpeg'):

  write_retry_params = gcs.RetryParams(backoff_factor=1.1)
  gcs_file = gcs.open(filename,
                      'w',
                      content_type=mime_type,
                      retry_params=write_retry_params)
  gcs_file.write(contents)
  gcs_file.close()

  # Maybe do other too stuff like make the file publicly
  # accessible

并调用它来写入文件。