AWS s3 python sdk code examples

Yet another easy-to-understand, easy-to-use aws s3 python sdk code examples.

github地址:https://github.com/garyelephant/aws-s3-python-sdk-examples.

"""
Yet another s3 python sdk example.
based on boto 2.27.0
"""

import time
import os
import urllib

import boto.s3.connection
import boto.s3.key

def test():
    print ‘--- running AWS s3 examples ---‘
    c = boto.s3.connection.S3Connection(‘<YOUR_AWS_ACCESS_KEY>‘, ‘<YOUR_AWS_SECRET_KEY>‘)

    print ‘original bucket number:‘, len(c.get_all_buckets())

    bucket_name = ‘yet.another.s3.example.code‘
    print ‘creating a bucket:‘, bucket_name
    try:
        bucket = c.create_bucket(bucket_name)
    except boto.exception.S3CreateError  as e:
        print ‘ ‘ * 4, ‘error occured:‘
        print ‘ ‘ * 8, ‘http status code:‘, e.status
        print ‘ ‘ * 8, ‘reason:‘, e.reason
        print ‘ ‘ * 8, ‘body:‘, e.body
        return

    test_bucket_name = ‘no.existence.yet.another.s3.example.code‘
    print ‘if you just want to know whether the bucket(\‘%s\‘) exists or not‘ % (test_bucket_name,),         ‘and don\‘t want to get this bucket‘
    try:
        test_bucket = c.head_bucket(test_bucket_name)
    except boto.exception.S3ResponseError as e:
        if e.status == 403 and e.reason == ‘Forbidden‘:
            print ‘ ‘ * 4, ‘the bucket(\‘%s\‘) exists but you don\‘t have the permission.‘ % (test_bucket_name,)
        elif e.status == 404 and e.reason == ‘Not Found‘:
            print ‘ ‘ * 4, ‘the bucket(\‘%s\‘) doesn\‘t exist.‘ % (test_bucket_name,)

    print ‘or use lookup() instead of head_bucket() to do the same thing.‘,         ‘it will return None if the bucket does not exist instead of throwing an exception.‘
    test_bucket = c.lookup(test_bucket_name)
    if test_bucket is None:
        print ‘ ‘ * 4, ‘the bucket(\‘%s\‘) doesn\‘t exist.‘ % (test_bucket_name,)

    print ‘now you can get the bucket(\‘%s\‘)‘ % (bucket_name,)
    bucket = c.get_bucket(bucket_name)

    print ‘add some objects to bucket ‘, bucket_name
    keys = [‘sample.txt‘, ‘notes/2006/January/sample.txt‘, ‘notes/2006/February/sample2.txt‘,           ‘notes/2006/February/sample3.txt‘, ‘notes/2006/February/sample4.txt‘, ‘notes/2006/sample5.txt‘]
    print ‘ ‘ * 4, ‘these key names are:‘
    for name in keys:
        print ‘ ‘ * 8, name

    filename = ‘./_test_dir/sample.txt‘
    print ‘ ‘ * 4, ‘you can contents of object(\‘%s\‘) from filename(\‘%s\‘)‘ % (keys[0], filename,)
    key = boto.s3.key.Key(bucket, keys[0])
    bytes_written = key.set_contents_from_filename(filename)
    assert bytes_written == os.path.getsize(filename), ‘    error occured:broken file‘

    print ‘ ‘ * 4, ‘or set contents of object(\‘%s\‘) by opened file object‘ % (keys[1],)
    fp = open(filename, ‘r‘)
    key = boto.s3.key.Key(bucket, keys[1])
    bytes_written = key.set_contents_from_file(fp)
    assert bytes_written == os.path.getsize(filename), ‘    error occured:broken file‘

    print ‘ ‘ * 4, ‘you can also set contents the remaining key objects from string‘
    for name in keys[2:]:
        print ‘ ‘ * 8, ‘key:‘, name
        key = boto.s3.key.Key(bucket, name)
        s = ‘This is the content of %s ‘ % (name,)
        key.set_contents_from_string(s)
        print ‘ ‘ * 8, ‘..contents:‘, key.get_contents_as_string()
        # use get_contents_to_filename() to save contents to a specific file in the filesystem.

    #print ‘You have %d objects in bucket %s‘ % ()    

    print ‘list all objects added into \‘%s\‘ bucket‘ % (bucket_name,)
    objs = bucket.list()
    for key in objs:
        print ‘ ‘ * 4, key.name

    p = ‘notes/2006/‘
    print ‘list objects start with \‘%s\‘‘ % (p,)
    objs = bucket.list(prefix = p)
    for key in objs:
        print ‘ ‘ * 4, key.name

    print ‘list objects or key prefixs like \‘%s/*\‘, something like what\‘s in the top of \‘%s\‘ folder ?‘ % (p, p,)
    objs = bucket.list(prefix = p, delimiter = ‘/‘)
    for key in objs:
        print ‘ ‘ * 4, key.name

    keys_per_page = 4
    print ‘manually handle the results paging from s3,‘, ‘ number of keys per page:‘, keys_per_page
    print ‘ ‘ * 4, ‘get page 1‘
    objs = bucket.get_all_keys(max_keys = keys_per_page)
    for key in objs:
        print ‘ ‘ * 8, key.name

    print ‘ ‘ * 4, ‘get page 2‘
    last_key_name = objs[-1].name   #last key of last page is the marker to retrive next page.
    objs = bucket.get_all_keys(max_keys = keys_per_page, marker = last_key_name)
    for key in objs:
        print ‘ ‘ * 8, key.name
    """
    get_all_keys() a lower-level method for listing contents of a bucket.
    This closely models the actual S3 API and requires you to manually handle the paging of results.
    For a higher-level method that handles the details of paging for you, you can use the list() method.
    """

    print ‘you must delete all objects in the bucket \‘%s\‘ before delete this bucket‘ % (bucket_name, )
    print ‘ ‘ * 4, ‘you can delete objects one by one‘
    bucket.delete_key(keys[0])
    print ‘ ‘ * 4, ‘or you can delete multiple objects using a single HTTP request with delete_keys().‘
    bucket.delete_keys(keys[1:])

    print ‘now you can delete the bucket \‘%s\‘‘ % (bucket_name,)
    c.delete_bucket(bucket)

    #references:
    #  [1] http://docs.pythonboto.org/
    #  [2] amazon s3 api references

if __name__ == ‘__main__‘:
    test()

转载本文请注明作者和出处[Gary的影响力]http://garyelephant.me,请勿用于任何商业用途!

Author: Gary Gao( garygaowork[at]gmail.com) 关注互联网、分布式、高性能、NoSQL、自动化、软件团队

支持我的工作:  https://me.alipay.com/garygao

AWS s3 python sdk code examples,布布扣,bubuko.com

时间: 2024-08-27 08:56:04

AWS s3 python sdk code examples的相关文章

Java vs. Python (1): Simple Code Examples

Some developers have claimed that Python is more productive than Java. It is dangerous to make such a claim, because it may take several days to prove that thoroughly. From a high level view, Java is statically typed, which means all variable names h

Python使用boto3操作AWS S3中踩过的坑

最近在AWS上开发部署应用. 看了这篇关于AWS中国区填坑的文章,结合自己使用AWS的经历,补充两个我自己填的坑. http://www.jianshu.com/p/0d0fd39a40c9?utm_source=tuicool&utm_medium=referral 1. V4 签名认证 官方文档中给出的例子: import boto3 s3 = boto3.resource('s3') s3.meta.client.upload_file('/tmp/hello.txt', 'mybucke

使用s3 java sdk 分片文件上传API 报‘SignatureDoesNotMatch’ 异常的定位及解决方案

import java.io.File; import com.amazonaws.AmazonClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.Upload; public class U

AWS S3使用小结

使用场景一:储存网站的图片,并能被任何人访问 1. 创建一个bucket,名字与需要绑定的域名一致. 例如,根域名是mysite.com,希望把所有图片放在pic.mysite.com下面,访问的时候用pic.mysite.com/a.jpg就能直接访问,那么这个bucket的名字就应该设置成pic.mysite.com 这时候就能在控制台上传文件了,当然做实际应用的话需要用他的SDK写程序来实现上传功能. 我们上传一个a.jpg,右边Properties里面给出了一个link "https:/

新浪微博python sdk 使用总结

1.先到新浪微博开放平台注册接入的应用,获取AppKey和AppSecret,并制定CallbackUrl(可以任意指定,当授权服务器授权后会跳到这个页面,并返回授权码code) 2.下载新浪微博python SDK并安装 安装步骤:解压缩文件,找到setup.py 执行 python setup.py install 将weibo.py安装到python的site-packages中 测试:import weibo 没有异常则说明安装成功! 3.要调用SDK的API,首先需要进行授权,新浪微博

aws s3 上传 binary 数据 (通过stringstream)

有个需求需要将二进制istream上传到s3上暂存,但苦于没能直接找到接口,官方提供的设置数据块的接口如下: inline void SetBody(const std::shared_ptr<Aws::IOStream>& body) { m_bodyStream = body; } 这个Aws::IOStream其实就是std::iostream的封装. 在实际寻找传入参数的时候没找到比较好的传入对象:fstream意味着我需要先将数据存到磁盘再去读取,感觉不是很好:而string

用Node完成AWS S3的Upload流程之全世界最简版

开场: 查了两天文档,Error了38次,最后索性去掉所有附加条件, 连界面也不要了,在命令行里跑通了一坨最干瘪的Upload流程! 还冒着热气…… 在此先做记录,明天可以搭配美美的界面继续调试了. 近来压抑的心情顿时舒畅了百分之十. 1. 注册以及相关配置: 注册一枚Amazon账户,如果你经常在Amazon上买买买, 那你其实已经有了Amazon的Retail账户,可以直接登录为AWS账户, 但要变身为这么高大上的账户,不出血怎么可能? 在这过程中,需要花费1美元的认证费用…… 我把信用卡的

七牛云存储Python SDK使用教程 - 上传策略详解

文 七牛云存储Python SDK使用教程 - 上传策略详解 七牛云存储 python-sdk 七牛云存储教程 jemygraw 2015年01月04日发布 推荐 1 推荐 收藏 2 收藏,2.7k 浏览 本教程旨在介绍如何使用七牛的Python SDK来快速地进行文件上传,下载,处理,管理等工作. 前言 我们在上面的两节中了解到,客户端上传文件时,需要从业务服务器申请一个上传凭证(Upload Token),而这个上传凭证是业务服务器根据上传策略(PutPolicy)来生成的,而这个生成过程中

[转]Java Code Examples for android.util.JsonReader

[转]Java Code Examples for android.util.JsonReader The following are top voted examples for showing how to use android.util.JsonReader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will b