Tạo function xoá dữ liệu

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.

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

  2. Ấn nút Create function LambdaConsole

  3. Nhập tên function: delete_document

  • Chọn Python 3.9 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 thực hiện lấy biến môi trường TABLE_NAMEpartition key and sort key từ event. Sau đó thêm xoá item có partition key and sort key khớp với input.

  1. Chúng ta cần thêm biến môi trường cho function. Ấn tab Configuration, sau đó chọn Environment variables ở menu phía bên trái. Ấn Edit

EnvironmentVariables

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

EnvironmentVariables

  1. Tiếp theo, thêm quyền cho function truy cập DynamoDB table
  • Ấn Permission ở bên menu trái
  • Ấn vào tên role mà lambda function đang thực hiện

Permission

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

Permission

  1. Chọn tab JSON. Sao chép đoạn json dưới đây vào editor
,
        {
            "Effect": "Allow",
            "Action": "dynamoDB:DeleteItem",
            "Resource": "arn:aws:dynamodb:REGION:ACCOUNT_ID:table/Documents"
        }

Thay REGIONACCOUNT_ID bằng vùng mà bạn tạo bảng và account id của bạn.

  • Ấn Review policy

Permission

  1. Ấn Save changes

Permission