我如何使用 boto3 触发 Lambda 函数

how I can trigger Lambda function using boto3

我有一个 s3 存储桶,这是我将上传文件的路径 dev/uploads/excel。现在我想添加一个触发器来调用我已经创建的 lambda 函数。是否有任何特定代码我必须 运行 一次才能使用 boto3 启用此功能的触发器?或者需要粘贴到某处?我不知道它是如何工作的?

您需要在 Lambda 函数上添加 S3 触发器并在您的代码中处理 S3 事件。

要创建 S3 触发器 select Lambda 控制台 left-hand 端的添加触发器选项。

因为你想触发新的上传,你可以创建这个事件来触发 PUT 事件。 对于前缀,您可以添加所需的路径:dev/uploads/excel

Python 中的 Lambda 示例:

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

此外,有很多文档对此进行了解释,例如以下文档:Tutorial: Using an Amazon S3 trigger to invoke a Lambda function