[英]AWS Lambda calling DynamoDB put_item gives syntax error
我使用 Python 創建了我的第一個 Lambda 以在名為Users的 DynamoDB 表中創建一個新條目,該表具有 String 類型的分區鍵UserId 。 我在我的 API 網關中使用 POST 方法調用它,使用測試 function 發送請求正文:
{
"email":"testemail",
"name":"testname testerson",
"password":"testpassword1"
}
該方法背后的想法是生成一個用於主鍵的 UUID,如果它已經在使用中,則再次生成它,直到它是唯一的。 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)
}
語法錯誤出現在包含'UserId' = user_id,
的行的日志中,但我不知道為什么。
任何幫助,將不勝感激!
有兩種定義字典文字的標准方法
Item={
'UserId' = user_id,
'name' = body['name'],
'email' = body['email'],
'password' = hashed,
'salt' = salt
}
這不是其中的一個。
你可以這樣做:
Item={
'UserId': user_id,
'name': body['name'],
'email': body['email'],
'password': hashed,
'salt': salt
}
或者:
Item=dict(
UserId=user_id,
name=body['name'],
email=body['email'],
password=hashed,
salt=salt
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.