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

亚马逊 s3 boto3 中 Client,Resource和Session 区别。

邓深
2023-12-01

boto3 中 Client,Resource和Session的不同。

boto3 英文官方文档链接 https://boto3.amazonaws.com/v1/documentation/api/latest/guide/resources.html

Resource 是 Amazon Web Services(AWS)的面向对象的接口。 与 Client 进行的原始低级调用相比,它们提供了面向对象的方法。 如果需要定义自己的用户和连接地址,可以通过使用Session 来定义 Resource

Resources represent an object-oriented interface to Amazon Web Services (AWS). They provide a higher-level abstraction than the raw, low-level calls made by service clients. To use resources, you invoke the resource() method of a Session and pass in a service name

Resource 用法

    session = Session(aws_access_key_id="aws_access_key_id",
                      aws_secret_access_key="aws_secret_access_key")
    s3 = session.resource('s3')
    bucket = s3.Bucket("bucket_name")
    
    for bucket in s3.buckets.all():
    	print(bucket.name)

Clients 为AWS提供的是 API 接口,用法和调用API接口类似。 Clients 是从JSON服务定义文件生成的。(可以参考swagger生成的client 理解)

Clients provide a low-level interface to AWS whose methods map close to 1:1 with service APIs. All service operations are supported by clients. Clients are generated from a JSON service definition file.

Clients 用法

Clients are created in a similar fashion to resources:

import boto3

# Create a low-level client with the service name
sqs = boto3.client('sqs')

It is also possible to access the low-level client from an existing resource:

# Create the resource
sqs_resource = boto3.resource('sqs')

# Get the client from the resource
sqs = sqs_resource.meta.client
 类似资料: