将Blobstore迁移到GCS:Google App Engine Python

5

这是我现有的用于将数据上传到blobstore的Python代码。

from google.appengine.api import files

def save_data_to_blob_store(data):
    # Create the file
    file_name = files.blobstore.create(mime_type='application/octet-stream')

    # Open the file and write to it
    with files.open(file_name, 'a') as f:
        f.write(data)

    # Finalize the file. Do this before attempting to read it.
    files.finalize(file_name)

    # Get the file's blob key
    blob_key = files.blobstore.get_blob_key(file_name)
    return str(blob_key)

现在我正在尝试废弃blobstore并转移到GCS。我写了一些代码,但是效果不如预期。

def save_data_to_gcs(request):
    file_name = '/gs/bucket-name-1/new_file' # change bucket/object names to suit your needs
    writable_file_name = files.gs.create(file_name, mime_type='application/octet-stream',
                                     acl='public-read')
    with files.open(writable_file_name, 'a') as f:
        f.write('Hello World!\n')
        f.write('This is a Google Cloud Storage object!\n')
    files.finalize(writable_file_name)

执行此过程时,GAE在生产环境中抛出错误,错误内容为:
Exception in request:
Traceback (most recent call last):
  File "/base/data/home/apps/s~bfsolu/248.371810019093562707/common/zip-packages/django-1.1.zip/django/core/handlers/base.py", line 92, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/base/data/home/apps/s~bfsolu/248.371810019093562707/myapp/utils.py", line 51, in save_data_to_gcs
    acl='public-read')
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/files/gs.py", line 326, in create
    return files._create(_GS_FILESYSTEM, filename=filename, params=params)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/files/file.py", line 647, in _create
    _make_call('Create', request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/files/file.py", line 252, in _make_call
    _raise_app_error(e)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/files/file.py", line 210, in _raise_app_error
    raise PermissionDeniedError(e)
 PermissionDeniedError: ApplicationError: 8

有人可以帮忙纠正我在save_data_to_gcs过程中的错误吗?非常感谢。

谢谢。


1
你是否已经激活了GCS(启用计费等)?在Google Cloud Console中,您是否已经授权您的应用程序访问您的存储桶?为此,请选择您的存储桶,单击“存储桶权限”,并添加新的“用户”权限,提供您的应用程序电子邮件地址(app-id@appspot.gserviceaccount.com),并将其设置为所有者。 - Mark Simpson
@MarkSimpson:谢谢,老兄。它像魅力一样运作。 我还需要一个帮助,如何获取文件记录的唯一键? - Niks Jain
好的,我已经将我的评论转换为下面的答案。请将其接受为正确答案。然后单独发布新问题。它与此问题无关。谢谢。 - Mark Simpson
2个回答

4
你需要激活你的项目以使用GCS。
然后在Google Cloud Console中授予你的应用程序使用你的存储桶的权限:
为此,选择你的存储桶,点击“Bucket Permissions”按钮,并添加新的“User”权限,提供你的应用程序电子邮件地址(app-id@appspot.gserviceaccount.com)并将其设置为所有者。

0

由于文件 API 在2015年9月已关闭,因此此方法不再可用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接