AWS Dynamobd
walterjesus88
Posted on July 4, 2024
import json
import boto3
from boto3.dynamodb.conditions import Key
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
def lambda_handler(event, context):
http_method = event['httpMethod']
if http_method == 'POST':
return create_user(event)
elif http_method == 'GET':
return get_user(event)
elif http_method == 'PUT':
return update_user(event)
elif http_method == 'DELETE':
return delete_user(event)
else:
return {
'statusCode': 405,
'body': json.dumps('Method Not Allowed')
}
def create_user(event):
body = json.loads(event['body'])
user_id = body['userId']
name = body['name']
age = body['age']
table.put_item(
Item={
'userId': user_id,
'name': name,
'age': age
}
)
return {
'statusCode': 201,
'body': json.dumps(f'User {user_id} created successfully')
}
def get_user(event):
user_id = event['queryStringParameters']['userId']
response = table.get_item(
Key={
'userId': user_id
}
)
if 'Item' in response:
return {
'statusCode': 200,
'body': json.dumps(response['Item'])
}
else:
return {
'statusCode': 404,
'body': json.dumps(f'User {user_id} not found')
}
def update_user(event):
body = json.loads(event['body'])
user_id = body['userId']
name = body.get('name')
age = body.get('age')
update_expression = 'set '
expression_attribute_values = {}
if name:
update_expression += 'name = :name, '
expression_attribute_values[':name'] = name
if age:
update_expression += 'age = :age, '
expression_attribute_values[':age'] = age
update_expression = update_expression.rstrip(', ')
table.update_item(
Key={'userId': user_id},
UpdateExpression=update_expression,
ExpressionAttributeValues=expression_attribute_values
)
return {
'statusCode': 200,
'body': json.dumps(f'User {user_id} updated successfully')
}
def delete_user(event):
user_id = event['queryStringParameters']['userId']
table.delete_item(
Key={
'userId': user_id
}
)
return {
'statusCode': 200,
'body': json.dumps(f'User {user_id} deleted successfully')
}
vicio de aws
💖 💪 🙅 🚩
walterjesus88
Posted on July 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.