将文件上传到谷歌云存储会在无对象URI上抛出boto.exception.InvalidUriError:new_key

时间:2015-06-29 00:52:44

标签: python google-cloud-storage

我的问题是我如何将文件上传到谷歌云存储。 即时通讯使用boto连接到gs并即时获取:

boto.exception.InvalidUriError: new_key on object-less URI 

这是我的代码:

import boto
import gcs_oauth2_boto_plugin
import os
import shutil
import StringIO
import tempfile
import time

def upload_file(filename, uri):
    temp_dir = os.getcwd()
    # The key-related functions are a consequence of boto's
    # interoperability with Amazon S3 (which employs the
    # concept of a key mapping to localfile).
    with open(os.path.join(temp_dir, filename), 'r') as localfile:
        uri.new_key().set_contents_from_file(localfile)
    print 'Successfully created "%s/%s"' % (
      uri.bucket_name, uri.object_name)

    shutil.rmtree(temp_dir)  # Don't forget to clean up!

# URI scheme for Google Cloud Storage.
GOOGLE_STORAGE = 'gs'
# URI scheme for accessing local files.
LOCAL_FILE = 'file'

# Fallback logic. In https://console.developers.google.com
# under Credentials, create a new client ID for an installed application.
# Required only if you have not configured client ID/secret in
# the .boto file or as environment variables.
CLIENT_ID = 'foo'
CLIENT_SECRET = 'bar'
gcs_oauth2_boto_plugin.SetFallbackClientIdAndSecret(CLIENT_ID, CLIENT_SECRET)

# Instantiate a BucketStorageUri object.
uri = boto.storage_uri('foobar', GOOGLE_STORAGE)

try:
    #list_buckets(uri)
    upload_file('kitten.jpg', uri)
except boto.exception.StorageCreateError, e:
  print 'Failed to create bucket:', e

1 个答案:

答案 0 :(得分:0)

使用它:

uri = boto.storage_uri('altitude-manage-dashboard/kitten.jpg', 'gs')