A bucket is a container used to store objects in Object Storage Service (OSS). Every object is contained in a bucket. This topic describes how to determine whether a bucket exists.
The following code provides an example on how to determine whether a specified bucket exists:
# -*- coding: utf-8 -*- import oss2 # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret') # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. # Set yourBucketName to the name of the bucket. bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName') def does_bucket_exist(bucket): try: bucket.get_bucket_info() except oss2.exceptions.NoSuchBucket: return False except: raise return True # Determine whether the specified bucket exists. If the bucket exists, true is returned. Otherwise, false is returned. exist = does_bucket_exist(bucket) if exist: print('bucket exist') else: print('bucket not exist')
For more information about the complete sample code that is used to determine whether a bucket exists, visit GitHub.