Home > database >  how I can trigger Lambda function using boto3
how I can trigger Lambda function using boto3

Time:02-23

I have a s3 bucket and this is path where I will upload a file dev/uploads/excel . Now I want to add a trigger to invoke a my already made lambda function. is there any specific code I have to run once to enable trigger for this function using boto3 ?or need to paste somewhere ? I am confuse how It will work ?

CodePudding user response:

You need to add a S3 trigger on the Lambda function and handle the S3 event in your code.

To create the S3 trigger select the Add trigger option on the left-hand side on the Lambda console.

enter image description here

Since you want to trigger off of new uploads, you can create this event to trigger off of the PUT event. For the prefix you can add the path you want: dev/uploads/excel

enter image description here

A Lambda example in Python:

def lambda_handler(event, context):
    #print("Received event: "   json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        print("CONTENT TYPE: "   response['ContentType'])
        return response['ContentType']
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e

Also, there a lot of docs explaining this, like the following one: Tutorial: Using an Amazon S3 trigger to invoke a Lambda function.

  • Related