Trong phần này chúng ta sẽ tạo function để xoá thông tin tài liệu được lưu trong DynamoDB table theo id của người dùng và tên tệp.
Mở bảng điều khiển AWS Lambda
Ấn nút Create function

Nhập tên function: delete_document

import json
import boto3
import os
client = boto3.resource('dynamodb')
def lambda_handler(event, context):
# TODO implement
table_name = os.environ['TABLE_NAME']
error = None
doc_pk = event['pathParameters']['id']
print("doc_pk ", doc_pk)
doc_sk = event['queryStringParameters']['file']
print("doc_sk ", doc_sk)
table = client.Table(table_name)
key = {
'user_id':doc_pk,
'file': doc_sk
}
try:
table.delete_item(Key = key)
except Exception as e:
error = e
except Exception as e:
error = e
if error is None:
message = 'delete document successful!'
else:
print(error)
message = 'delete document fail'
return {
'statusCode': 200,
'body': message,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
}

Đoạn code trên thực hiện lấy biến môi trường TABLE_NAME và partition key and sort key từ event. Sau đó thêm xoá item có partition key and sort key khớp với input.

TABLE_NAME làm key


,
{
"Effect": "Allow",
"Action": "dynamoDB:DeleteItem",
"Resource": "arn:aws:dynamodb:REGION:ACCOUNT_ID:table/Documents"
}
Thay REGION và ACCOUNT_ID bằng vùng mà bạn tạo bảng và account id của bạn.

