所以我尝试使用 put_item 同步 Dynamodb 表。但我遇到了一个问题。
Invalid type for parameter Item.Artist, value: No One You Know, type: <class 'str'>, valid types: <class 'dict'>
从阅读文档来看,使用 put_item 时它需要一个字典,所以本质上是这样的:
'{'Artist': {'S': 'No One You Know'},'SongTitle': {'S': 'Call Me Today'}}'
以便正确添加。
这是我的代码:
#!/usr/bin/python3
import boto3
source = boto3.resource('dynamodb', 'us-east-1')
dest = boto3.client('dynamodb', 'us-west-2')
def sync(source, dest):
table = source.Table("myMusic")
scan_kwargs = {
'ProjectionExpression': "Artist, SongTitle"
}
done = False
start_key = None
while not done:
if start_key:
scan_kwargs['ExclusiveStartKey'] = start_key
response = table.scan(**scan_kwargs)
for item in response['Items']:
dest.put_item(TableName="myMusic", Item=item)
#print(item)
start_key = response.get('LastEvaluatedKey', None)
done = start_key is None
sync(source, dest)
因此,如果我取消注释打印语句,我会得到:
{'Artist': 'No One You Know', 'SongTitle': 'Call Me Today'}
有什么方法可以清理输出或添加额外所需的“S”,或者我是否以错误的方式处理这个问题?
在代码的某个阶段,您将拥有
item = {'Artist': 'No One You Know', 'SongTitle': 'Call Me Today'}
当您取消注释 print 语句时,您所说的内容将会被打印。
使用以下代码片段:
newItem = { 'Artist': {}, 'SongTitle': {} }
newItem['Artist']['S'] = item['Artist']
newItem['SongTitle']['S'] = item['SongTitle']
所以整个代码变成:
#!/usr/bin/python3
import boto3
source = boto3.resource('dynamodb', 'us-east-1')
dest = boto3.client('dynamodb', 'us-west-2')
def sync(source, dest):
table = source.Table("myMusic")
scan_kwargs = {
'ProjectionExpression': "Artist, SongTitle"
}
done = False
start_key = None
while not done:
if start_key:
scan_kwargs['ExclusiveStartKey'] = start_key
response = table.scan(**scan_kwargs)
for item in response['Items']:
####################### SNIPPET #######################
newItem = { 'Artist': {}, 'SongTitle': {} }
newItem['Artist']['S'] = item['Artist']
newItem['SongTitle']['S'] = item['SongTitle']
####################### SNIPPET #######################
dest.put_item(TableName="myMusic", Item=newItem)
#print(item)
start_key = response.get('LastEvaluatedKey', None)
done = start_key is None
我在使用 RestAPI 测试 Lambda 函数时遇到了类似的问题。我正在使用curl来测试。我通过在curl中使用--data-raw选项成功地遵守了put_item语法,而无需修改我的函数代码。
下面是针对 Windows 卷曲,因此我需要使用双引号来括起数据,而不是单引号和转义字符 \ 以便在我的数据中使用双引号。
curl api_url --data-raw "{\"uId\": {\"S\": \"4\"}, \"Add\": {\"SS\": [\"地址 1\",\"地址 2\"]}, \"电子邮件\": {\"S\": \“[电子邮件受保护]\”},\“暴徒\”:{\“N \”:\“6512345678 \”},\“名称\”: {\"S\": \"Vijaya R\"}}"
对于非 Windows 系统来说这应该可以工作(未经测试)。
curl api_url --data-raw '{"uId": {"S": "4"}, "添加": {"SS": [“地址1”,“地址2”]},“电子邮件”:{“S”: "[电子邮件受保护]"}, "mob": {"N": "6512345678"}, "name": {“S”:“Vijaya R”}}'