首页 > 解决方案 > 每当在源存储桶中上传 zip 文件时,AWS lambda 函数都会触发从源 s3 到目标 s3 的复制

问题描述

我创建了一个基于事件的触发 lambda 函数,只要将 zip 文件加载到源 s3 存储桶中,它就会将 zip 文件从源 s3 复制到目标 s3。下面是python中的lambda函数:

from __future__ import print_function
import json
import urllib
import boto3
print('Loading function')
s3 = boto3.client('s3')

def lambda_handler(event, context):
  bucket = event['Records'][0]['s3']['bucket']['name']
  key = urllib.unquote_plus(event['Records'][0]['s3']['object'] 
      ['key'].encode("utf8"))
  target_bucket =  'bucket name'
  copy_source = {'Bucket' :bucket , 'Key' : key}
  try:
    response = s3.get_object(Bucket=bucket, Key=key)
    print("CONTENT TYPE: " + response['ContentType'])
    return response['ContentType']
    print("copying from source to target")
    s3.copy_object(Bucket=target_bucket, 
            Key=key,CopySource=copy_source)
  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

以下是我通过执行代码得到的错误消息:

'Records': KeyError Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 13, in lambda_handler
    bucket = event['Records'][0]['s3']['bucket']['name']
KeyError: 'Records'

任何解决此问题的帮助将不胜感激。

标签: pythonamazon-web-servicesamazon-s3aws-lambda

解决方案


推荐阅读