python - Python boto3 异常处理
问题描述
我想创建一个具有多个属性的 S3 存储桶:
def create_s3_bucket(name):
s3Client = boto3.client('s3')
try:
s3Client.create_bucket(
Bucket=name,
ACL="private",
CreateBucketConfiguration={
'LocationConstraint': 'eu-central-1',
},
)
except ClientError as e:
print(e)
try:
s3Client.put_public_access_block(
Bucket=name,
PublicAccessBlockConfiguration={
'BlockPublicAcls': True,
'IgnorePublicAcls': True,
'BlockPublicPolicy': True,
'RestrictPublicBuckets': True
}
)
except ClientError as e:
print(e)
try:
s3Client.put_bucket_versioning(
Bucket=name,
VersioningConfiguration={
'Status': 'Enabled'
}
)
except ClientError as e:
s3Client.put_bucket_tagging(
Bucket=name,
Tagging={
'TagSet': [
{
'Key': 'firstTag',
'Value': 'firstValue'
},
]
}
)
except ClientError as e:
print(e)
到目前为止,这有效。我的问题是:有没有更好、更优雅的方式来处理 ClientError,因为我一直在代码中重复自己?如果我将每个 API 调用放入一个 try catch 块中,那么可能会出现一个调用没有发生事件的情况。
解决方案
您可以将所有这些放在同一个 try 块中,这最终会阻止它尝试无法执行的功能(即从未创建过存储桶)。
如果引发异常,它应该返回除打印之外的其他内容以识别此失败,以防止函数的调用者继续执行逻辑。
此外,在您的异常声明中,如果您的存储桶已创建但无法继续,您可以回滚。
此代码可能如下所示
def create_s3_bucket(name):
s3Client = boto3.client('s3')
try:
s3Client.create_bucket(
Bucket=name,
ACL="private",
CreateBucketConfiguration={
'LocationConstraint': 'eu-central-1',
},
)
s3Client.put_public_access_block(
Bucket=name,
PublicAccessBlockConfiguration={
'BlockPublicAcls': True,
'IgnorePublicAcls': True,
'BlockPublicPolicy': True,
'RestrictPublicBuckets': True
}
)
s3Client.put_bucket_versioning(
Bucket=name,
VersioningConfiguration={
'Status': 'Enabled'
}
)
s3Client.put_bucket_tagging(
Bucket=name,
Tagging={
'TagSet': [
{
'Key': 'firstTag',
'Value': 'firstValue'
},
]
}
)
except ClientError as e:
print(e)
#Do some tidy up (delete bucket or notify)
return false
return true
推荐阅读
- google-cloud-platform - GCP /dev/sdb1 /home 已满,但我没有项目
- excel - 如何将值与值列表进行比较
- javascript - 错误的onselect显示?角 2+
- r - 过滤变量以连接不同维度的两个数据框
- session - 绘制亚洲时段的高点和低点
- python - 列表中的嵌套字符串 - 需要拆分嵌套字符串以帮助将其转换为数据框
- javascript - 为什么这会导致串联而不是将两个数字相加?
- c# - 用于噪声生成的散列函数
- c# - c# Revit API 任务对话框,带有多行计数元素
- python - 我的 pip 安装在其他 PATH 中,我不希望我不知道如何修改它