Trong phần này, chúng ta sẽ tạo một hàm để xóa thông tin tài liệu trong bảng DynamoDB theo ID người dùng và tên tệp.
Mở bảng điều khiển AWS Lambda
Nhấn nút Create function

Nhập tên hàm: 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 lấy biến môi trường TABLE_NAME, partition key và sort key do người dùng cung cấp. Sau đó, đoạn code thực hiện lệnh xóa mục trong bảng dựa trên partition key và sort key đó.

TABLE_NAME vào ô key


{
"Effect": "Allow",
"Action": "dynamoDB:DeleteItem",
"Resource": "arn:aws:dynamodb:REGION:ACCOUNT_ID:table/Documents"
}
Thay REGION và ACCOUNT_ID bằng khu vực đã tạo bảng và ID tài khoản của bạn.

