"使用boto3处理S3文件上传过程中的ClientError"

2024-06-28 20:53:33 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用无效的凭据发出boto3上载请求时,我希望使用自定义格式来显示错误消息。我正试图通过以下方式来实现这一点

try: 
    s3_client = boto3.client('s3', aws_access_key_id='blah', aws_secret_access_key='blah', region_name='us-west-2')
    s3_client.upload_file('test', 'bucket', 'test')

except ClientError as e:  # handle aws s3 exceptions
     msg = e.response.get('Error', {}).get('Message', 'Unknown')
     code = e.response.get('Error', {}).get('Code', 'Unknown')
     print('Failed to copy to S3 bucket: {msg} ({code})'.format(msg=msg, code=code))

运行这个我得到一个类似于这个的回溯(只包括异常)

^{pr2}$

我的假设是在upload_file调用期间,当另一个请求在后台异步运行时,将引发ClientError。一旦ClientError开始处理,就会引发S3UploadFileError,这将导致上面的回溯。有什么方法可以忽略S3UploadFileError,因为这是多余的,并且与自定义格式的ClientError没有相同的属性。在


Tags: keytestclientawsgets3access格式
1条回答
网友
1楼 · 发布于 2024-06-28 20:53:33

这个怎么样

try: 
    s3_client = boto3.client('s3', aws_access_key_id='blah', aws_secret_access_key='blah', region_name='us-west-2')
    s3_client.upload_file('test', 'bucket', 'test')

except S3UploadFailedError as e:
     raise CustomException(msg ='unknown error', Code = 0;)

except ClientError as e:  # handle aws s3 exceptions
     msg = e.response.get('Error', {}).get('Message', 'Unknown')
     code = e.response.get('Error', {}).get('Code', 'Unknown')
     raise CustomException(msg = msg, Code = code;)
except:
     print('Failed to copy to S3 bucket: {msg} ({code})'.format(msg=msg, code=code))

相关问题 更多 >