当前位置: 首页 > 工具软件 > boto > 使用案例 >

Boto2 s3访问示例

宇文修文
2023-12-01
    import boto
    import boto.s3.connection
    ############### Replace these with your configrations ####################
    CONS_AK = 'RC35MU8KM1PMEQ4EFD46'
    CONS_SK = 'Fg1KO10FS4uIPzSoKenmKAR2YHt052rM9u8VDik9'
    
    s3_conn = boto.connect_s3(
            aws_access_key_id=CONS_AK,
            aws_secret_access_key=CONS_SK,
            host='yhg-2',
            port=80,
            is_secure=False,
            calling_format=boto.s3.connection.OrdinaryCallingFormat()
            )
    ##########################################################################
    # create bucket
    bucket_name = 'hehe'
    print 'Create bucket ', bucket_name
    mb = s3_conn.create_bucket(bucket_name)
    # list bucket
    print 'List all buckets:'
    buckets = s3_conn.get_all_buckets()
    for bucket in buckets:
        print bucket.name
    # put object from file
    print "Put object from local file"
    f_obj_name = './s3-demon.py'
    f_key = mb.new_key(f_obj_name)
    f_key.set_contents_from_filename(f_obj_name)
    # put object from string
    print "Put object from string"
    s_obj_name = 'string'
    s_key = mb.new_key(s_obj_name)
    # set user defined metadata key/value in request header
    my_header = {
         'x-amz-meta-joseph': 'Yang Honggang'
     }
    s_key.set_contents_from_string('hello, world!', headers = my_header)
    # list objects in bucket
    keys = mb.list()
    print "List all keys in bucket:"
    key_names = []
    for key in keys:
        key_names.append(key.name)
        print "name: ", key.name, "size: ", key.size
    # get object to file
    local_file = './local_file'
    s_key.get_contents_to_filename(local_file)
    # get object to string
    string = s_key.get_contents_as_string()
    print "key ", f_obj_name, ": ", string
    # set bucket-wide ACL
    mb.set_acl('public-read-write')
    # set object-specific ACL
    mb.set_acl('private', s_obj_name)
    # get object's metadata
    md = s_key.get_metadata('joseph')
    print "Get metadata: ", md
    # modify user defined metadata k/v
    print "Modify a existd obj's user defined metadata"
    ### local update
    s_key.metadata.update({'joseph': 'Hehe',
                           'javen' : 'WJ'
                          })
    ### boto gives back an object without ANY metadata
    s_key_new = s_key.copy(s_key.bucket.name, s_key.name, s_key.metadata, preserve_acl=True)
    # read the latest metadata
    string = s_key_new.get_contents_as_string()
    md = s_key_new.get_metadata('joseph')
    print "Get latest metadata: "
    print "\t<joseph,", md, ">"
    md = s_key_new.get_metadata('javen')
    print "\t<javen,", md, ">"
    # delete all keys
    ret = mb.delete_keys(key_names)
    print "Delete all keys in bucket: "
    print "\t success: ", ret.deleted
    print "\t failed: ", ret.errors
    
    # delete bucket
    print 'Delete bucket ', mb.name
    s3_conn.delete_bucket(mb)

 类似资料: