我第一次尝试使用 update_item 在 dynamodb 中保存数据。在我项目的另一个领域,我成功地使用了 put_item() 。对于这个新的代码区域,我只保存更改的项目,将未更改的项目留在数据库中。因此,我需要使用 update_item()。但是,我似乎无法弄清楚为什么我的语法对于 API 调用不正确。我直接从 Amazon UI 使用它。
这是我的python代码:
from __future__ import print_function
import json
import boto3
print('Loading function')
def saveScreenData(event, context):
dynamodb = boto3.client('dynamodb', region_name='us-east-1', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")
print('The event: {}'.format(event))
key = {}
key['UID'] = event['uid']
key['screenId'] = event['screenid']
print('Key: {}'.format(key))
for item, val in event.items():
if item != 'uid' and item != 'screenid':
print("Saving!")
response = dynamodb.update_item({
"TableName" : "ScreenData",
"Key" : key,
"UpdateExpression" : "SET #attrName = :attrValue",
"ExpressionAttributeNames" : {
"#attrName" : item
},
"ExpressionAttributeValues" : {
":attrValue" : val
}
})
print('Response: {}'.format(response))
return response
这是输出:
START RequestId: 2da9412a-b03d-11e7-9dc8-8fcb305833f6 Version: $LATEST
The event: {'article': '<p>↵ First!↵</p>', 'screenid': '13', 'uid': '0', 'section1': '<h1>↵ Second↵</h1>'}
Key: {'UID': '0', 'screenId': '13'}
Saving!
update_item() only accepts keyword arguments.: TypeError
Traceback (most recent call last):
File "/var/task/saveScreenData.py", line 30, in saveScreenData
":attrValue" : val
File "/var/runtime/botocore/client.py", line 310, in _api_call
"%s() only accepts keyword arguments." % py_operation_name)
TypeError: update_item() only accepts keyword arguments.
END RequestId: 2da9412a-b03d-11e7-9dc8-8fcb305833f6
我研究了 update_item 文档 ( https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html ) 并根据 mkobit ( https://stackoverflow.com/users/627727/mkobit ) 的 SO 问答对我的查询进行了建模: https://stackoverflow.com/a/30604746/8027640
我尝试了语法的变体,包括添加字典 {"S": "maybe this works"} 而不是我的变量 val,并且还尝试将变量更改为一些静态内容以查看它是否有效,但没有运气。
显然这是一个语法问题,但我一直无法找到它。有什么建议吗?
最佳答案
我认为您使用的示例是基于 boto2
的,它与 boto3
相比具有完全不同的界面。
相反,请查看 the boto3 documentation ,您应该使用关键字参数作为错误状态(并且您正在使用字典)。 您的请求应大致如下所示:
response = dynamodb.update_item(
TableName="ScreenData",
Key=key,
UpdateExpression="SET #attrName = :attrValue",
ExpressionAttributeNames={
"#attrName" : item
},
ExpressionAttributeValues={
":attrValue" : val
}
)
关于python - Amazon lambda dynamodb update_item() 只接受关键字参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46735558/