【发布时间】:2020-07-25 07:07:23
【问题描述】:
我想创建一个具有多个属性的 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 块中,那么可能会出现一个调用没有发生事件的情况。
【问题讨论】:
-
如果
create_bucket失败,put_public_access_block将如何工作?你需要充实你的程序在错误情况下的行为。 -
我需要指定我的问题:如果存储桶例如已经存在然后它抛出一个异常。但这应该可以防止将存储桶属性与后续 API 调用放在一起。
-
如果你想检查bucket是否存在并完成你的功能,为什么不直接
return如果它不存在呢?
标签: python python-3.x amazon-web-services exception boto3