Basic
Configuration
boto3 use AWS CLI's configuration file by default. (.aws/config and .aws/credentials)
In credential files, best to have a default profile. Otherwise we need to specify which profile we want to use.
Connect to AWS
import boto3
s3 = boto3.resource('s3')
# Print out bucket names
for bucket in s3.buckets.all():
print(bucket.name)
# Upload a new file
data = open('test.jpg', 'rb')
s3.Bucket('my-bucket').put_object(Key='test.jpg', Body=data)
High level resources and low level client
Two way to use boto3 to connect to AWS service:
- use low level client
client = boto3.client('s3')
- use high level resource
s3 = boto3.resource('s3')
Session
Use session to control the connection setting, like indicate profile etc.
A session manages state about a particular configuration. By default a session is created for you when needed. However it is possible and recommended to maintain your own session(s) in some scenarios. Sessions typically store:
- Credentials
- Region
- Other configurations
Using the default session
sqs = boto3.client('sqs')
s3 = boto3.resource('s3')
Custom Session
It is also possible to manage your own session and create clients or resources from it:
session = boto3.session.Session(profile_name="name") # can add parameter, like profile
sqs = session.client('sqs')
s3 = session.resource('s3')