Skip to main content
 首页 » 编程设计

python之使用 Python 的谷歌云存储

2025年05月04日10daizhj

我按照手册搭建了谷歌云存储所需的环境。 我已经安装了“gsutil”并设置了所有路径。 然而,当我尝试运行下面的代码时,我的 gsutil 运行良好,

#!/usr/bin/python 
 
import StringIO 
import os 
import shutil 
import tempfile 
import time 
from oauth2_plugin import oauth2_plugin 
 
import boto 
 
# URI scheme for Google Cloud Storage. 
GOOGLE_STORAGE = 'gs' 
# URI scheme for accessing local files. 
LOCAL_FILE = 'file' 
 
uri=boto.storage_uri('sangin2', GOOGLE_STORAGE) 
 
try: 
    uri.create_bucket() 
    print "done!" 
except boto.exception.StorageCreateError, e: 
    print "failed" 

它给出“403 访问被拒绝”错误。

  Traceback (most recent call last): 
      File "/Volumes/WingIDE-101-4.0.0/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 23, in <module> 
      File "/Users/lsangin/gsutil/boto/boto/storage_uri.py", line 349, in create_bucket 
        return conn.create_bucket(self.bucket_name, headers, location, policy) 
      File "/Users/lsangin/gsutil/boto/boto/gs/connection.py", line 91, in create_bucket 
        response.status, response.reason, body) 
    boto.exception.GSResponseError: GSResponseError: 403 Forbidden 
      <?xml version='1.0' encoding='UTF-8'?><Error><Code>AccessDenied</Code><Message>Access denied.</Message></Error> 

由于我是新手,所以我很难弄清楚原因。 有人能帮我吗? 谢谢。

请您参考如下方法:

boto 库应该会自动找到并使用您的 $HOME/.boto 文件。要检查的一件事:确保您正在使用的项目设置为旧版访问的默认项目(在 API 控制台中,单击“存储访问”并验证它是否显示“这是旧版访问的默认项目”) .当我设置不正确并且我按照您引用的创建存储桶示例进行操作时,我也会收到 403 错误,但是,这在 gsutil 中对您有用但在直接使用 boto 时不起作用是没有意义的。

尝试在实例化 storage_uri 对象时添加“debug=2”,如下所示:

uri = boto.storage_uri(name, GOOGLE_STORAGE, debug=2) 

这将在 stdout 上生成一些额外的调试信息,然后您可以将这些信息与类似的、有效的 gsutil 示例(通过 gsutil -D mb )的调试输出进行比较。