问题:资源,客户端和会话之间的boto3差异?

我在Ubuntu 16.04 LTS中使用Python 2.7.12。我正在通过以下链接学习如何使用boto3:https ://boto3.readthedocs.io/en/latest/guide/quickstart.html#using-boto-3 。我的疑问是何时使用资源,客户端或会话及其各自的功能。

I am using Python 2.7.12 in Ubuntu 16.04 LTS. I’m learning how to use boto3 from the following link: https://boto3.readthedocs.io/en/latest/guide/quickstart.html#using-boto-3. My doubt is when to use resource, client, or session, and their respective functionality.


回答 0

这里是有关ClientResourceSession的所有更详细的信息。

客户:

  • 低级AWS服务访问
  • 从AWS 服务描述生成
  • 向开发人员展示botocore客户端
  • 通常使用AWS服务API 1:1映射
  • 客户端支持所有AWS服务操作
  • 蛇形方法名称(例如ListBuckets API => list_buckets方法)

以下是客户端级别访问S3存储桶的对象(最多1000 **)的示例:

import boto3

client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
    obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
    print(content['Key'], obj_dict['LastModified'])

**您必须使用分页器,或实现自己的循环,如果数量超过1000,则使用连续标记重复调用list_objects()。

资源:

  • 更高级别的,面向对象的API
  • 根据资源描述生成
  • 使用标识符和属性
  • 有行动(对资源的操作)
  • 公开子资源和AWS资源集合
  • 不提供AWS服务的100%API覆盖率

以下是使用资源级别访问S3存储桶的对象(全部)的等效示例:

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
    print(obj.key, obj.last_modified)

请注意,在这种情况下,您无需进行第二次API调用即可获取对象。您可以将其作为存储桶中的集合使用。这些子资源集合是延迟加载的。

您可以看到Resource该代码的版本更简单,更紧凑并且具有更多功能(它可以为您分页)。Client如果要包括分页,代码的版本实际上比上面显示的要复杂。

会议:

  • 存储配置信息(主要是凭据和所选区域)
  • 允许您创建服务客户端和资源
  • boto3在需要时为您创建一个默认会话

re:Invent video入门视频是了解这些boto3概念的有用资源。

Here’s some more detailed information on what Client, Resource, and Session are all about.

Client:

  • low-level AWS service access
  • generated from AWS service description
  • exposes botocore client to the developer
  • typically maps 1:1 with the AWS service API
  • all AWS service operations are supported by clients
  • snake-cased method names (e.g. ListBuckets API => list_buckets method)

Here’s an example of client-level access to an S3 bucket’s objects (at most 1000**):

import boto3

client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
    obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
    print(content['Key'], obj_dict['LastModified'])

** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.

Resource:

  • higher-level, object-oriented API
  • generated from resource description
  • uses identifiers and attributes
  • has actions (operations on resources)
  • exposes subresources and collections of AWS resources
  • does not provide 100% API coverage of AWS services

Here’s the equivalent example using resource-level access to an S3 bucket’s objects (all):

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
    print(obj.key, obj.last_modified)

Note that in this case you do not have to make a second API call to get the objects; they’re available to you as a collection on the bucket. These collections of subresources are lazily-loaded.

You can see that the Resource version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client version of the code would actually be more complicated than shown above if you wanted to include pagination.

Session:

  • stores configuration information (primarily credentials and selected region)
  • allows you to create service clients and resources
  • boto3 creates a default session for you when needed

A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.


回答 1

我将尽力解释它。因此,不能保证实际条款的准确性。

会话是启动与AWS服务的连接的地方。例如,以下是使用默认凭据配置文件的默认会话(例如〜/ .aws / credentials,或使用IAM实例配置文件假设您的EC2)

sqs = boto3.client('sqs')
s3 = boto3.resource('s3')

由于默认会话仅限于使用的配置文件或实例配置文件,因此有时您需要使用自定义会话来覆盖默认会话配置(例如region_name,endpoint_url等),例如

# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')

# you have two choices of create custom client session. 
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')

资源:这是建议使用的高级服务类。这使您可以绑定特定的AWS资源并将其传递,因此您只需要使用此抽象,就不必担心要指向哪个目标服务。从会话部分可以注意到,如果您有一个自定义会话,则只需传递此抽象对象,而不必担心所有自定义区域等的传递。以下是一个复杂的示例,例如

import boto3 
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket') 
video_bucket = video_s3.Bucket('videobucket')

# just pass the instantiated bucket object
def list_bucket_contents(bucket):
   for object in bucket.objects.all():
      print(object.key)

list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)

客户端是低级别的对象。对于每个客户端调用,您需要显式指定目标资源,指定的服务目标名称必须传递很长时间。您将失去抽象能力。

例如,如果仅处理默认会话,则该外观类似于boto3.resource。

import boto3 
s3 = boto3.client('s3')

def list_bucket_contents(bucket_name):
   for object in s3.list_objects_v2(Bucket=bucket_name) :
      print(object.key)

list_bucket_contents('Mybucket') 

但是,如果要列出不同区域中存储桶中的对象,则需要指定客户端所需的显式存储桶参数。

import boto3 
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')

# you must pass boto3.Session.client and the bucket name 
def list_bucket_contents(s3session, bucket_name):
   response = s3session.list_objects_v2(Bucket=bucket_name)
   if 'Contents' in response:
     for obj in response['Contents']:
        print(obj['key'])

list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket') 

I’ll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.

Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )

sqs = boto3.client('sqs')
s3 = boto3.resource('s3')

Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.

# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')

# you have two choices of create custom client session. 
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')

Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.

import boto3 
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket') 
video_bucket = video_s3.Bucket('videobucket')

# just pass the instantiated bucket object
def list_bucket_contents(bucket):
   for object in bucket.objects.all():
      print(object.key)

list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)

Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.

For example, if you only deal with the default session, this looks similar to boto3.resource.

import boto3 
s3 = boto3.client('s3')

def list_bucket_contents(bucket_name):
   for object in s3.list_objects_v2(Bucket=bucket_name) :
      print(object.key)

list_bucket_contents('Mybucket') 

However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.

import boto3 
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')

# you must pass boto3.Session.client and the bucket name 
def list_bucket_contents(s3session, bucket_name):
   response = s3session.list_objects_v2(Bucket=bucket_name)
   if 'Contents' in response:
     for obj in response['Contents']:
        print(obj['key'])

list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket') 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。