簡體   English   中英

Python boto3 異常處理

[英]Python boto3 exception handling

我想創建一個具有多個屬性的 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 塊中,這最終會阻止它嘗試無法執行的功能(即從未創建過存儲桶)。

如果引發異常,它應該返回除打印之外的其他內容以識別此失敗,以防止 function 的調用者繼續執行該邏輯。

此外,在您的異常聲明中,如果您的存儲桶已創建但無法繼續,您可以回滾。

此代碼可能如下所示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM