简体   繁体   English

Python会将文件存储到Google云端存储中

[英]Python urlretrieve a file to Google Cloud Storage

I am trying to deploy an application on the GAE. 我正在尝试在GAE上部署应用程序。
My python script downloads images using the urlretrieve function from the urllib.request package: 我的python脚本使用urllib.request包中的urlretrieve函数下载图像:

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

It works fine, as long as I am running the script locally (to save the images locally), but I am unable to find an alternative to doing the same with the GCS. 它工作正常,只要我在本地运行脚本(在本地保存图像),但我无法找到对GCS执行相同操作的替代方法。

I would appreciate if someone could point me towards how to achieve this. 如果有人能指出我如何实现这一目标,我将不胜感激。

Thanks! 谢谢!

The documentation shows how to use a couple of simple methods to read and write to Cloud Storage buckets. 文档显示了如何使用几种简单的方法来读取和写入云存储桶。

Instead of urlretrieve , just grab the image's contents and then write the response to a file in Cloud Storage. 而不是urlretrieve ,只需抓取图像的内容,然后将响应写入云存储中的文件。

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

And say you modify the Cloud Storage samples slightly to: 并且说您稍微修改云存储样本:

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

And call that to write the file. 并调用它来写入文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM