0 python amazon-s3 amazon-web-services aws-lambda
当我通过 s3brower 将文件上传到 s3 时,我的 python lambda 脚本将处理这些文件。如果我一次上传数千个文件,可能会出现一些失败例如,我上传1651张图片,lambda失败了十六次,一张名为
test.jpg
在我的lambda脚本中,首先检查文件是否存在,
client.head_object(Bucket=bucket_tmp,Key='test.jpg')
cloudwatch日志显示错误 An error occurred (404) when calling the HeadObject operation: Not Found
然后我在我的计算机中执行 client.head_object(Bucket=bucket_tmp,Key='test.jpg') ,没问题,然后我可以在我的s3存储桶中看到它。
我在中国,这会是网络问题吗?当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)
Run Code Online (Sandbox Code Playgroud)
了解更多: https: //docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html