Reputation: 95
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. I'm calling it using a POST method in my API Gateway using the test function to send a request body of:
{
"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. The lambda function is:
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.
Any help would be appreciated!
Upvotes: 0
Views: 514
Reputation: 21275
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
}
Upvotes: 3