首页 > 解决方案 > AWS lambda:调用 HeadObject 操作时发生错误 (404):未找到

问题描述

当我通过 s3brower 将文件上传到 s3 时,我的 python lambda 脚本将处理这些文件。如果我一次上传数千个文件,可能会出现一些失败,例如,我上传了 1651 张图片,lambda 失败了 16 次,一个名为 test.jpg

在我的 lambda 脚本中,首先检查文件是否存在,
client.head_object(Bucket=bucket_tmp,Key='test.jpg')
cloudwatch log 显示错误 An error occurred (404) when calling the HeadObject operation: Not Found 然后我 client.head_object(Bucket=bucket_tmp,Key='test.jpg') 在我的计算机中执行,没关系,然后我可以在我的 s3 存储桶中看到它。

我在中国,会不会是网络问题?lambda处理图片时,图片没有上传?

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

解决方案


我们在使用 lambda 时遇到了类似的问题,我们跟进了 AWS 支持,发现这是由于 S3 中文件的最终一致性造成的。S3 事件在实际文件在 S3 中完全可用之前触发,通常发生在我们一次上传大量文件时。

我们通过引入指数退避(2,4,8,16.. 秒)的重试解决了这个问题。

示例 S3 下载代码(您可以类似地使用 client.head_object 调用):

#Method with retries
def download_file_s3(client,bucket,s3_path,local_path,retries = 3):
    i = 0
    sleep = 2
    while(i <= retries):
        try:
            client.download_file(bucket,s3_path,local_path)
            break
        except Exception as e:            
            print("404 file not found !!!")
            i = i+1
            if i>retries:
                raise Exception(traceback.format_exc())
            time.sleep(sleep)
            sleep = sleep*2
            print("retry: "+str(i))

#Sample call
client = boto3.client('s3')
download_file_s3(client,bucket,s3_path,local_path,retries)

阅读更多:https ://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html


推荐阅读