programing tip

리소스, 클라이언트 및 세션 간의 boto3의 차이점은 무엇입니까?

itbloger 2020. 6. 4. 19:13
반응형

리소스, 클라이언트 및 세션 간의 boto3의 차이점은 무엇입니까?


우분투 16.04 LTS에서 Python 2.7.12를 사용하고 있습니다. https://boto3.readthedocs.io/en/latest/guide/quickstart.html#using-boto-3 링크에서 boto3을 사용하는 방법을 배우고 있습니다 . 리소스, 클라이언트 또는 세션 및 해당 기능을 언제 사용해야하는지 의심의 여지가 있습니다.


Client , ResourceSession 에 대한 자세한 정보는 다음과 같습니다 .

고객:

  • 저수준 AWS 서비스 액세스
  • AWS 서비스 설명 에서 생성
  • botocore 클라이언트를 개발자에게 노출
  • 일반적으로 1 : 1을 AWS 서비스 API와 매핑
  • 모든 AWS 서비스 작업은 클라이언트에서 지원합니다
  • 뱀으로 둘러싸인 메소드 이름 (예 : ListBuckets API => list_buckets 메소드)

다음은 S3 버킷 객체에 대한 클라이언트 수준 액세스의 예입니다 (최대 1000 **).

import boto3

client = boto3.client('s3')
response = client.list_objects(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 ()를 반복적으로 호출하여 paginator 를 사용 하거나 자체 루프를 구현해야합니다.

자원:

  • 더 높은 수준의 객체 지향 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는 필요할 때 기본 세션을 만듭니다.

이러한 boto3 개념에 대해 자세히 알아볼 수있는 유용한 리소스는 소개 re : Invent 비디오 입니다.


가능한 한 간단하게 설명하겠습니다. 따라서 실제 항의 정확성을 보장하지 않습니다.

세션 은 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')

Resource : This is the high level service class recommended to be used. This allow you to tied particular AWS resources and pass it along, so you just use this abstraction than worry which target services is pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying of all custom region,etc to pass along. Following is a complicate 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 lost the abstraction ability.

For example, if you only deal with 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 bucket in different region, you need to specify explicit bucket parameter required for 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') 

참고URL : https://stackoverflow.com/questions/42809096/difference-in-boto3-between-resource-client-and-session

반응형