简体   繁体   English

如何在AWS中捕获Stream事件 lambda python

[英]How to capture the Stream event in AWS lambda python

I have dynamo db which name as "test-dynamo"我有名为“test-dynamo”的发电机数据库

I have enable Manage stream我已启用管理 stream 在此处输入图像描述

I need to capture in lambda function. If any update/Insert has happend to this dynamo table I need to see in the lambda我需要在 lambda function 中捕获。如果此发电机表发生任何更新/插入,我需要在 lambda 中查看

def gettable(table_name, dynamodb_client):
        response = dynamodb_client.get_item(
            TableName=table_name,
            Key={
                'id': {'S': key
                            }})
        return response

def lambda_handler(event, context):
    dynamodb_client = boto3.client('dynamodb')
    boto3.resource('dynamodb')
    res= gettable("test-dynamo",dynamodb_client )
    print('event', event )

You can checkout this documentation page for configuring the same.您可以查看此文档页面以进行配置。

for example once you subscirbe your lambda function to the corresponding dynamodb stream you create in cloudformation,例如,一旦您将 lambda function 订阅到您在 cloudformation 中创建的相应 dynamodb stream,

    rLoggingFunction:
        Type: AWS::Lambda::Function
        Properties:
        Runtime: python3.7
        Timeout: '300'
        Handler: index.handler
        Role: !GetAtt rLambdaRole.Arn
        Code:
            ZipFile: |
            import logging

            LOGGER = logging.getLogger()
            LOGGER.setLevel(logging.INFO)

            def handler(event, context):
                LOGGER.info('Received Event: %s', event)
                for rec in event['Records']:
                LOGGER.info('Record: %s', rec) 
    ....
    rDynamoDBTable:
        Type: AWS::DynamoDB::Table
        Properties:
        AttributeDefinitions:
            - AttributeName: id
            AttributeType: S
        KeySchema:
            - AttributeName: id
            KeyType: HASH
        ProvisionedThroughput:
            ReadCapacityUnits: 1
            WriteCapacityUnits: 1
        StreamSpecification:
            StreamViewType: NEW_AND_OLD_IMAGES

    rDynamoDBTableStream:
        Type: AWS::Lambda::EventSourceMapping
        Properties:
        # The maximum number of DB items to send to Lambda
        BatchSize: 1
        Enabled: True
        EventSourceArn: !GetAtt rDynamoDBTable.StreamArn
        FunctionName: !GetAtt rLoggingFunction.Arn
        # Always start at the tail of the Stream
        StartingPosition: LATEST

There is a full example via serverless for the same.通过无服务器有一个完整的例子。

You can do it using simple code once you enable stream in DynamoDB:在 DynamoDB 中启用 stream 后,您可以使用简单的代码来完成此操作:

import json
import boto3
from boto3.dynamodb.conditions import Key
def lambda_handler(event, context):
      print('##Below Event occured')
      print(event)

This will print the latest event in cloudwatch logs.这将在 cloudwatch 日志中打印最新事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM