boto3 resource vs client vs session:
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.
Boto3 Client Example:
1 2 3 4 5 6 7 |
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']) |
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.
Boto3 Resource Example:
1 2 3 4 5 6 |
import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket('mybucket') for obj in bucket.objects.all(): print(obj.key, obj.last_modified) |
Session:
A session manages state about a particular configuration. By default, a session is created for you when needed. However, it’s possible and recommended that in some scenarios you maintain your own session.
Boto3 Session Example:
1 2 3 4 5 6 7 8 |
import boto3 session = boto3.Session(region_name='ap-south-1',aws_access_key_id=os.environ['AWS_ACCESS_KEY'],aws_secret_access_key=os.environ['AWS_SECRET_KEY']) s3 = session.resource('s3') bucket = s3.Bucket('mybucket') for obj in bucket.objects.all(): print(obj.key, obj.last_modified) |