简体   繁体   English

如何在发回响应之前等待 python lambda 处理程序中的所有事件?

[英]How to wait for all events in a python lambda handler before sending back a response?

I have an AWS Lambda function in python that uses SSM to run scripts in an EC2 instance.我在 Python 中有一个 AWS Lambda 函数,它使用 SSM 在 EC2 实例中运行脚本。 The script after execution creates a folder in S3 (random name).执行后的脚本在 S3 中创建一个文件夹(随机名称)。 Once the folder gets created, the lambda function needs to return a response with the name of the S3 folder.创建文件夹后,lambda 函数需要返回带有 S3 文件夹名称的响应。

When I check the Cloudwatch logs, I can see the name of the folder in one of the events.当我检查 Cloudwatch 日志时,我可以在其中一个事件中看到文件夹的名称。 But the Lambda function returns a 200 before all events have run.但是 Lambda 函数在所有事件运行之前返回 200。 How do I make the handler wait till all events are complete before returning the response/200?如何让处理程序在返回响应/200 之前等待所有事件完成?

import boto3
import time

def lambda_handler(event, context):
     print('event is: ', event)
     if 'number' in event.keys():
        command = 'python lambda_test.py ' + str(event['number']);
        workingDirectory = '/home/ubuntu/src';
        executionTimeout = "3600";
        ssm = boto3.client('ssm');
        ssmresponse = ssm.send_command(InstanceIds=['I-***********a1'], DocumentName='AWSLambdaSampleRun', Parameters= { 'commands': [command], 'workingDirectory': [workingDirectory], 'executionTimeout' : [executionTimeout] }, ServiceRoleArn='arn:aws-us-west-1:sts::***************:assumed-role/lambda/sample', OutputS3BucketName = 'sample-ui' )
     records = [x for x in event.get('Records', []) if x.get('eventName') == 'ObjectCreated:Put']
     print("records : ", records)
     if records:
        awsRegion = records[0].get('awsRegion', '')
        info = records[0].get('s3', {})
        file_key = info.get('object', {}).get('key')
        bucket_name = info.get('bucket', {}).get('name')
        message = {
        'body' : "Script execution completed. See https://console.amazonaws.com/s3/buckets/" + bucket_name + "/" + file_key.replace('err', 'out') + "/?region=" + awsRegion + "&tab=overview  for complete output"
        }
        print message
        return message

An earlier event has the parameter ('event is: ', {u'number': u'1'})较早的事件具有参数('event is: ', {u'number': u'1'})

Post script execution, the event holds the name of the s3 key -脚本执行后,事件包含 s3 密钥的名称 -

('event is: ', {u'Records': [{u'eventVersion': u'2.1', u'eventTime': u'2019-04-15T04:48:06.217Z', u'requestParameters': {u'sourceIPAddress': u'**.**.**.***'}, u's3': {u'configurationId': u'*************', u'object': {u'eTag': u'*********8a11', u'sequencer': u'*********83C', u'key': u'**********', u'size': 5946}, u'bucket': {u'arn': u'arn:aws-us-****', u'name': u'sample', u'ownerIdentity': {u'principalId': u'AWS:********'}}, u's3SchemaVersion': u'1.0'}, u'responseElements': {u'x-amz-id-2': u'**/**/**/**=', u'x-amz-request-id': u'***'}, u'awsRegion': u'us-west-1', u'eventName': u'ObjectCreated:Put', u'userIdentity': {u'principalId': u'AWS:**:I-**'}, u'eventSource': u'aws:s3'}]})

https://pypi.org/project/waiting/ https://pypi.org/project/waiting/

Check this out.看一下这个。 I ran into a similar situation recently where I was testing an event driven lambda.我最近遇到了类似的情况,当时我正在测试一个事件驱动的 lambda。

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

相关问题 AWS Reactive Response 处理程序下载带有 WARN“订阅者在所有事件发布之前取消”的部分文件 - AWS Reactive Response handler downloads partial file with WARN "Subscriber cancelled before all events were published" lambda 可以在不关闭会话的情况下返回响应并等待新主体吗? - Can a lambda return a response and wait for a new body without closing the session? aws cloudformation lambda python 错误处理程序 - aws cloudformation lambda python bad handler 在使用 reactjs 发送 POST 请求之前,我如何等待 firebase 检查用户是否有效? - how can i wait for firebase to check the user is valid before sending a POST request with reactjs? 如何等待firebase存储上传图片后再使用? - How to wait for firebase storage to upload image before using it? 如何在执行任务之前等待多个 firebase 查询完成? - How to wait for multiple firebase queries to finish before executing a task? 如何从 lambda 的 ALB 响应中删除标头 - How to remove headers form ALB response from lambda 如何通过 python lambda 函数运行 shell 命令? - How to run shell command through python lambda funciton? 如何在 AWS Lambda 中将消息记录到错误日志中的 Python - How to log messages to error log in Python in AWS Lambda 如何找到第二次登录时间之前的事件总数 - How to find the total number of events before the second login time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM