云存储:如何为Python Boto库设置服务帐户凭据

4
我正在跟随这篇教程,将一个文件上传到我手动创建的存储桶中:https://cloud.google.com/storage/docs/xml-api/gspythonlibrary 我似乎在设置服务帐户或用户帐户的凭据时遇到了问题。 我想在 Web 服务器上使用它,所以最好使用服务帐户进行设置。
我在 Console 中使用 API 管理器创建了一个 API 并下载了 JSON 文件。 同时,我的 gcloud auth 是使用我的 OAUTH 登录设置的。 我尝试过 gsutil config -e,但出现错误:
CommandException: OAuth2 is the preferred authentication mechanism with the Cloud SDK. Run "gcloud auth login" to configure authentication, unless you want to authenticate with an HMAC access key and secret, in which case run "gsutil config -a".

我还尝试使用以下命令对服务账户进行身份验证:gcloud auth activate-service-account --key-file <json file>,但是用python boto仍无法启用访问权限。我还将ID和Key从~/.config/gcloud/复制到了~/.boto,但这也没有奏效。我不确定该如何设置Python服务器以访问云存储进行身份验证。我没有使用App Engine,而是使用Cloud Compute来设置Web服务器。

下面是我的源代码:
import boto
import gcs_oauth2_boto_plugin
import os
import shutil
import StringIO
import tempfile
import time

CLIENT_ID = 'my client id from ~/.config/gcloud/credentials'
CLIENT_SECRET = 'my client secret from ~/.config/gcloud/credentials'
gcs_oauth2_boto_plugin.SetFallbackClientIdAndSecret(CLIENT_ID, CLIENT_SECRET)

uri = boto.storage_uri('', 'gs')
project_id = 'my-test-project-id'
header_values = {"x-test-project-id": project_id}
# If the default project is defined, call get_all_buckets() without arguments.
for bucket in uri.get_all_buckets(headers=header_values):
    print bucket.name

最近的错误:

Traceback (most recent call last):
  File "upload/uploader.py", line 14, in <module>
    for bucket in uri.get_all_buckets(headers=header_values):
  File "/Users/ankitjain/dev/metax/venv/lib/python2.7/site-packages/boto/storage_uri.py", line 574, in get_all_buckets
    return conn.get_all_buckets(headers)
  File "/Users/ankitjain/dev/metax/venv/lib/python2.7/site-packages/boto/s3/connection.py", line 444, in get_all_buckets
    response.status, response.reason, body)
boto.exception.GSResponseError: GSResponseError: 403 Forbidden
<?xml version='1.0' encoding='UTF-8'?><Error><Code>InvalidSecurity</Code><Message>The provided security credentials are not valid.</Message><Details>Incorrect Authorization header</Details></Error>

你的代码在哪里运行?如果它在GCE或GAE上,Google应用程序默认凭据是推荐的身份验证方法。https://developers.google.com/identity/protocols/application-default-credentials - Dagang
我想在GCE上运行此代码,但也需要一个本地开发环境。文档中没有描述如何在本地环境下工作的内容。 - Ankit
这是您正在寻找的内容吗?https://cloud.google.com/compute/docs/api/how-tos/authorization#gcloud_auth_login - Dagang
1个回答

0

经过一些实验后,我放弃了使用GCE库上传数据到云存储。实际上,我发现使用AWS boto上传到云存储效果更好。我所要做的就是在s3库中指定Google的主机:

conn = boto.connect_s3(app.config['S3_KEY'], app.config['S3_SECRET'], "c.storage.googleapis.com")
bucket = conn.get_bucket(app.config['S3_BUCKET'], validate=False)

我使用了在Google文档中描述的方式生成的HMAC凭证。参考链接: https://cloud.google.com/storage/docs/migrating


等一下,你是在使用谷歌的密钥和密码吗? - frmsaul

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