[英]AWS Lambda calling DynamoDB put_item gives syntax error
I've created my first Lambda with Python to create a new entry in a DynamoDB table called Users , which has Partition key UserId of type String.我使用 Python 创建了我的第一个 Lambda 以在名为Users的 DynamoDB 表中创建一个新条目,该表具有 String 类型的分区键UserId 。 I'm calling it using a POST method in my API Gateway using the test function to send a request body of:我在我的 API 网关中使用 POST 方法调用它,使用测试 function 发送请求正文:
{
"email":"testemail",
"name":"testname testerson",
"password":"testpassword1"
}
The idea behind the method is to generate a UUID to use for the primary key, and on the occurrence of it already being in use, generate it again until it is unique.该方法背后的想法是生成一个用于主键的 UUID,如果它已经在使用中,则再次生成它,直到它是唯一的。 The lambda function is: lambda function 是:
def create_user(event, context):
status_code = 0
response = ''
body = event['body']
# check all required fields are present
if all(key in body.keys() for key in ['email', 'password', 'name']):
# generate salt and hashed password
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(body['password'], salt)
# get users table from dynamodb
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
inserted = False
while not inserted:
user_id = uuid.uuid4().hex
try:
response = table.put_item(
Item={
'UserId' = user_id,
'name' = body['name'],
'email' = body['email'],
'password' = hashed,
'salt' = salt
},
ConditionExpression = 'attribute_not_exists(UserId)'
)
except Exception as e:
if e.response['Error']['Code'] == "ConditionalCheckFailedException":
continue
status_code = 500
response = 'Could not process your request'
break
else:
status_code = 200
response = 'Account successfully created'
inserted = True
else:
status_code = 400
response = 'Malformed request'
return {
'statusCode': status_code,
'body': json.dumps(response)
}
The syntax error appears in the logs on the line containing 'UserId' = user_id,
, but I have no idea why.语法错误出现在包含'UserId' = user_id,
的行的日志中,但我不知道为什么。
Any help would be appreciated!任何帮助,将不胜感激!
There are 2 standard ways of defining dictionary literals有两种定义字典文字的标准方法
Item={
'UserId' = user_id,
'name' = body['name'],
'email' = body['email'],
'password' = hashed,
'salt' = salt
}
This is not one of them.这不是其中的一个。
You can either do:你可以这样做:
Item={
'UserId': user_id,
'name': body['name'],
'email': body['email'],
'password': hashed,
'salt': salt
}
Or:或者:
Item=dict(
UserId=user_id,
name=body['name'],
email=body['email'],
password=hashed,
salt=salt
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.