如何从The Files API迁移到Google云端存储?

时间:2015-05-20 07:44:41

标签: google-app-engine google-cloud-storage blobstore

我昨天收到了Google的消息,称7月28日将禁用Files API,建议迁移到Google云端存储。

目前我以下列方式使用Files API - 收到电子邮件后,我将其附件(仅限图片)保存到blobstore -

from google.appengine.api import files

bs_file = files.blobstore.create(mime_type=ctype, _blobinfo_uploaded_filename='screenshot_'+image_file_name)
try:
    with files.open(bs_file, 'a') as f:
        f.write(image_file)
    files.finalize(bs_file)
    blob_key = files.blobstore.get_blob_key(bs_file)

稍后,我访问blobstore并将相同的图像附加到我发送的另一封邮件中:

attachments = []
for at_blob_key in message.attachments:
    blob_reader = blobstore.BlobReader(at_blob_key)
    blob_info = blobstore.BlobInfo.get(at_blob_key)
    if blob_reader and blob_info:
        filename = blob_info.filename
        attachments.append((filename, blob_reader.read()))
if len(attachments) > 0:
    email.attachments = attachments
email.send()

现在,我应该使用Google云端存储而不是Blobstore。 Google云存储不是免费的,因此我必须启用结算功能。目前我的Blobstore存储数据是0.27Gb,虽然很小,但看起来我不需要付出太多。但是我害怕启用结算功能,因为我的代码的其他部分可能会产生巨额费用(而且似乎无法为Google云端存储启用结算)。

那么,在我的情况下,有没有办法继续使用Blobstore进行文件存储?除了Google云端存储(Google云端硬盘驱动器)之外,我还可以免费使用其他什么?

1 个答案:

答案 0 :(得分:2)

以下示例使用GCS默认存储桶来存储屏幕截图。默认存储桶具有免费配额。

from google.appengine.api import app_identity
import cloudstorage as gcs

default_bucket = app_identity.get_default_gcs_bucket_name()
image_file_name = datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S') + '_' + image_file_name # GCS filename should be unique
gcs_filename = '/%s/screenshot_%s' % (default_bucket, image_file_name)
with gcs.open(gcs_filename, 'w', content_type=ctype) as f:
    f.write(image_file)

blob_key = blobstore.create_gs_key('/gs' + gcs_filename)
blob_key = blobstore.BlobKey(blob_key) # if should be stored in NDB