Tạo hàm xóa dữ liệu

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.

  1. Mở bảng điều khiển AWS Lambda

  2. Nhấn nút Create function LambdaConsole

  3. Nhập tên hàm: delete_document

  • Chọn Python 3.14 cho mục Runtime
  • Nhấn nút Create function

CreateFunction

  1. Nhập đoạn code sau cho tệp lambda_function.py:
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': '*'
            },
        }
  • Sau đó ấn Deploy

CreateFunction

Đ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 đó.

  1. Chúng ta cần thêm biến môi trường cho hàm. Nhấn tab Configuration, sau đó chọn Environment variables ở menu bên trái. Nhấn Edit

EnvironmentVariables

  1. Nhấn nút Add environment variable
  • Nhập TABLE_NAME vào ô key
  • Nhập tên bảng DynamoDB vừa tạo vào ô giá trị
  • Nhấn Save

EnvironmentVariables

  1. Tiếp theo, thêm quyền cho hàm để truy cập bảng DynamoDB
  • Nhấn Permissions ở menu bên trái
  • Nhấn vào tên role thực thi của hàm Lambda

Permission

  1. Mở rộng AWSLambdaBasicExecutionRole…, sau đó ấn Edit

Permission

  1. Sao chép đoạn JSON dưới đây vào trình chỉnh sửa
        {
            "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.

  • Nhấn Next

Permission

  1. Nhấn Save changes

Permission