无法使用 python 从 AWS dynamodb get_item?
Not able to get_item from AWS dynamodb using python?
我是 dynamodb 的新手,正在尝试从 dynamodb 获取数据。
This is my table with "topic" as a primary hash key
我的python代码
import boto3
from boto3 import dynamodb
from boto3.session import Session
from boto3.dynamodb.conditions import Key, Attr
dynamodb_session = Session(aws_access_key_id='XXXXXXXXXXXXXXX',
aws_secret_access_key='XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
region_name='us-east-1')
dynamodb = dynamodb_session.resource('dynamodb')
table=dynamodb.Table('Garbage_collector_table')
my_topic = "$aws/things/garbage_collector_thing/shadow/update/accepted"
response = table.get_item(TableName='Garbage_collector_table', Key={'topic':my_topic})
for res in response:
print "result ",res
我收到以下错误
Traceback (most recent call last):
File "get-data-dynamodb-boto3.py", line 19, in <module>
response = table.get_item(TableName='Garbage_collector_table', Key={'topic': my_topic}) File
"/usr/local/lib/python2.7/dist-packages/boto3/resources/factory.py",
line 518, in do_action
response = action(self, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/boto3/resources/action.py",
line 83, in __call__
response = getattr(parent.meta.client, operation_name)(**params) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line
258, in _api_call
return self._make_api_call(operation_name, kwargs) File /usr/local/lib/python2.7/dist-packages/botocore/client.py", line 548,
in _make_api_call
raise ClientError(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred
(ValidationException) when calling the GetItem operation: The provided
key element does not match the schema
我的代码中是否遗漏了什么?
您正在混合具有不同方法的资源对象和客户端对象。 .
资源的正确语法是:
response = table.get_item(Key={'topic': my_topic})
但我个人建议使用 boto 客户端:
client = boto3.client('dynamodb')
response = client.get_item(TableName='Garbage_collector_table', Key={'topic':{'S':str(my_topic)}})
http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html
您还可以查询数据库:
from boto3.dynamodb.conditions import Key
table = dynamodb.Table(table_name)
response = table.query(
KeyConditionExpression=Key('topic').eq(my_topic)
)
items = response['Items']
if items:
return items[0]
else:
return []
来源:https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.04.html
假设您在 table.
中只有分区键(又名散列键)
import boto3
dynamodb = boto3.resource('dynamodb',region_name='ap-southeast-2')
table = dynamodb.Table('my-table')
key = {}
key['key'] = 'my-key'
print(key)
response = table.get_item(Key=key)
print(response['Item'])
这里有实际例子:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/dynamodb.html
对于你的情况,你需要这样做:
response = table.get_item(TableName='Garbage_collector_table', Key={'topic': my_topic})
# Have the IAM role containing policy *AmazonDynamoDBFullAccess* assigned to your lambda function
import boto3
def lambda_handler(event, context):
try:
dynamodb_client = boto3.client('dynamodb')
response = dynamodb_client.get_item(
TableName="Garbage_collector_table",
Key={
'topic':
{'S':str(my_topic)}
}
)
except Exception as error:
print(error)
raise
else:
print(f'Response = {response}')
return response
如果您也有排序键,那么:
dynamodb = boto3.client('dynamodb', region_name=AWS_REGION, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCCESS_KEY)
response = dynamodb.get_item(
TableName=str(os.environ['DYNAMODB_TABLE']),
Key={'task_id' : {
'S' : str(task_id)
},
'mac' : {
'S' : 'AA-00-04-00-XX-YX'
}
}
)
我是 Lucid-Dynamodb 的作者,它是 AWS DynamoDB 的极简包装器。使用我的库可以轻松解决此问题。
参考: https://github.com/dineshsonachalam/Lucid-Dynamodb#4-read-an-item
from LucidDynamodb.Operations import DynamoDb
import os
import logging
logging.basicConfig(level=logging.INFO)
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
if __name__ == "__main__":
db = DynamoDb(region_name="us-east-1",
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
item = db.read_item(
TableName="test",
Key={
'topic': "1"
})
if(item != None):
logging.info("Item: {}".format(item))
else:
logging.warning("Item doesn't exist")
我是 dynamodb 的新手,正在尝试从 dynamodb 获取数据。
This is my table with "topic" as a primary hash key
我的python代码
import boto3
from boto3 import dynamodb
from boto3.session import Session
from boto3.dynamodb.conditions import Key, Attr
dynamodb_session = Session(aws_access_key_id='XXXXXXXXXXXXXXX',
aws_secret_access_key='XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
region_name='us-east-1')
dynamodb = dynamodb_session.resource('dynamodb')
table=dynamodb.Table('Garbage_collector_table')
my_topic = "$aws/things/garbage_collector_thing/shadow/update/accepted"
response = table.get_item(TableName='Garbage_collector_table', Key={'topic':my_topic})
for res in response:
print "result ",res
我收到以下错误
Traceback (most recent call last):
File "get-data-dynamodb-boto3.py", line 19, in <module>
response = table.get_item(TableName='Garbage_collector_table', Key={'topic': my_topic}) File
"/usr/local/lib/python2.7/dist-packages/boto3/resources/factory.py",
line 518, in do_action
response = action(self, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/boto3/resources/action.py",
line 83, in __call__
response = getattr(parent.meta.client, operation_name)(**params) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line
258, in _api_call
return self._make_api_call(operation_name, kwargs) File /usr/local/lib/python2.7/dist-packages/botocore/client.py", line 548,
in _make_api_call
raise ClientError(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the GetItem operation: The provided key element does not match the schema
我的代码中是否遗漏了什么?
您正在混合具有不同方法的资源对象和客户端对象。
资源的正确语法是:
response = table.get_item(Key={'topic': my_topic})
但我个人建议使用 boto 客户端:
client = boto3.client('dynamodb')
response = client.get_item(TableName='Garbage_collector_table', Key={'topic':{'S':str(my_topic)}})
http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html
您还可以查询数据库:
from boto3.dynamodb.conditions import Key
table = dynamodb.Table(table_name)
response = table.query(
KeyConditionExpression=Key('topic').eq(my_topic)
)
items = response['Items']
if items:
return items[0]
else:
return []
来源:https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.04.html
假设您在 table.
中只有分区键(又名散列键)import boto3
dynamodb = boto3.resource('dynamodb',region_name='ap-southeast-2')
table = dynamodb.Table('my-table')
key = {}
key['key'] = 'my-key'
print(key)
response = table.get_item(Key=key)
print(response['Item'])
这里有实际例子: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/dynamodb.html
对于你的情况,你需要这样做:
response = table.get_item(TableName='Garbage_collector_table', Key={'topic': my_topic})
# Have the IAM role containing policy *AmazonDynamoDBFullAccess* assigned to your lambda function
import boto3
def lambda_handler(event, context):
try:
dynamodb_client = boto3.client('dynamodb')
response = dynamodb_client.get_item(
TableName="Garbage_collector_table",
Key={
'topic':
{'S':str(my_topic)}
}
)
except Exception as error:
print(error)
raise
else:
print(f'Response = {response}')
return response
如果您也有排序键,那么:
dynamodb = boto3.client('dynamodb', region_name=AWS_REGION, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCCESS_KEY)
response = dynamodb.get_item(
TableName=str(os.environ['DYNAMODB_TABLE']),
Key={'task_id' : {
'S' : str(task_id)
},
'mac' : {
'S' : 'AA-00-04-00-XX-YX'
}
}
)
我是 Lucid-Dynamodb 的作者,它是 AWS DynamoDB 的极简包装器。使用我的库可以轻松解决此问题。
参考: https://github.com/dineshsonachalam/Lucid-Dynamodb#4-read-an-item
from LucidDynamodb.Operations import DynamoDb
import os
import logging
logging.basicConfig(level=logging.INFO)
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
if __name__ == "__main__":
db = DynamoDb(region_name="us-east-1",
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
item = db.read_item(
TableName="test",
Key={
'topic': "1"
})
if(item != None):
logging.info("Item: {}".format(item))
else:
logging.warning("Item doesn't exist")