Skip to content

Instantly share code, notes, and snippets.

@amui
Last active May 12, 2023 17:18
Show Gist options
  • Select an option

  • Save amui/154d88b9290402d6667a4d93756327e0 to your computer and use it in GitHub Desktop.

Select an option

Save amui/154d88b9290402d6667a4d93756327e0 to your computer and use it in GitHub Desktop.
Comparing boto3 resource vs client
# Boto3 examples showing difference between client and resource
#
import boto3
from boto3.dynamodb.conditions import Key
from botocore.config import Config
from pprint import pprint
my_config = Config(
region_name = 'us-east-1'
)
# Using DDB Table Resource
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table = dynamodb.Table('test-table')
response = table.query(
KeyConditionExpression=Key('PK').eq('d570e177-0378-44b3-82fb-2d08dfd4d254') & Key('SK').begins_with('NODE#')
)
pprint(response)
# Example: Updating an item in DDB
response = table.update_item(
Key={
'PK': 'd570e177-0378-44b3-82fb-2d08dfd4d254',
'SK': 'INFO'
},
UpdateExpression="SET session_code = :code",
ExpressionAttributeValues={
":code": "12345"
},
ReturnValues="UPDATED_NEW"
)
print(response)
# Using DDB Client
dynamodb = boto3.client('dynamodb', config=my_config)
response = dynamodb.query(
TableName='test-table',
KeyConditionExpression="#pk = :uuid AND begins_with(#sk, :prefix)",
ExpressionAttributeValues={
":uuid": {"S": "d570e177-0378-44b3-82fb-2d08dfd4d254"},
":prefix": {"S": "NODE#"}
},
ExpressionAttributeNames={
"#pk": "PK",
"#sk": "SK"
}
)
pprint(response)
###############
# Using EC2 Resource
ec2 = boto3.resource('ec2', region_name='us-east-1')
instance = ec2.Instance('i-000000000XXXXXXXX')
print(instance.private_ip_address)
# Using EC2 Client
ec2 = boto3.client('ec2', config=my_config)
response = ec2.describe_instances(
InstanceIds=['i-000000000XXXXXXXX']
)
pprint(response['Reservations'][0]['Instances'][0]['PrivateIpAddress'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment