使用 boto3 调用 S3 对象存储

概念解释

  • S3 对象存储

    遵循 Amazon S3 协议的对象存储服务

  • boto3

    基于s3协议实现了客户端API的 Python SDK,用于调用对象存储服务

  • Endpoint

    我们在调用s3对象存储的代码中使用的“Endpoint”,是指对象存储对外服务的访问域名

  • Bucket

    Bucket 是指对象存储上的存储空间,可理解为存放对象的“容器”,一个使用对象存储的用户可以拥有多个Bucket。主流的云服务提供商,都会支持用户对特定的Bucket进行访问权限的配置。

  • Object

    用户存储在对象存储上的每个文件都是一个 Object,每个Object 有一个键名/健值。对象可以是文本、图片、音频、视频或者网页等。

    使用简单对象上传方式时,对象大小限制在5GB以内。

    使用分块上传时,每块的大小限制在5GB以内,且分块数量需要小于10000个,即最大上传对象约为48.82TB。

S3 中没有文件夹。只是大多数可用的S3浏览器工具都显示了一部分的键名,并用斜杠分隔为文件夹。

安装 boto3

pip 安装

pip install boto3

源码安装

git clone https://github.com/boto/boto3.git && cd boto3 && sudo python setup.py install

使用boto3

接下来我们用代码演示一下,怎么使用 boto3

# 初始化 client
access_key = 'AKID10zuoeooooooooooooooooooooo' # ak
secret_key = 'nlbPCvHWkoooooooooooooooooooooo'     # sk
s3_host = 'cos.ap-hangzhou.myqcloud.com'           # Endpoint
s3client = boto3.client('s3',aws_secret_access_key = secret_key,aws_access_key_id = access_key,endpoint_url = s3_host)
# 遍历 bucket
list_buckets = s3client.list_buckets()
print(list_buckets)


# 遍历 bucket下的文件(对象)
bucket_name = 'cxy-1300123456'
file_list = []

response = s3client.list_objects_v2(
    Bucket=bucket_name,
    # MaxKeys=1000  # 返回数量,如果为空则为全部
)
file_desc = response['Contents']
for f in file_desc:
    print('file_name:{},file_size:{}'.format(f['Key'], f['Size']))
    file_list.append(f['Key'])
print(file_list)
bucket_name = "chenxy-1300123456"
local_file = "./tmp/hello.txt"
oss_key = "hello.txt"

# 上传文件
s3client.upload_file(local_file, bucket_name, oss_key)

# 下载文件
s3client.download_file(bucket_name, oss_key, local_file)

更多 boto3支持的方法,参见:https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html?highlight=put_object#client

猜你喜欢

转载自blog.csdn.net/chenxy02/article/details/129149231
今日推荐