python - 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处理图片时,图片没有上传?
解决方案
我们在使用 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
推荐阅读
- swift - 如何将当前日期与用户输入日期进行比较?
- date - Formik Yup 日期验证 - 接受欧洲 DD/MM/YYYY 格式
- c# - 从超过 100 亿个数字的双打流中计算运行中位数
- gradle - 停止执行 finalizedBy 任务,或仅在某个条件下执行后续任务
- c++ - 改进解决方案
- react-native - React Native RNDateTimePicker:无法选择日期
- python - 删除 txt 文件中特定字符之间的所有内容
- python - 为什么gdb和python中的十六进制地址添加不一样
- python - 为什么我的极小极大算法没有做出完美的一步 - 1D Chess?
- android - 如何使用特定片段开始活动