Use is_bucket_exist to check whether a specified bucket exists. The method returns a boolean.
Prerequisites
Before you begin, ensure that you have:
The
oss:GetBucketAclpermission on the target bucket. For details, see Attach a custom policy to a RAM user.Access credentials configured in environment variables. For details, see Configure access credentials.
Method definition
is_bucket_exist(bucket: str, request_payer: str | None = None, **kwargs) → boolRequest parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
bucket | str | Yes | The name of the bucket. |
Return value
| Type | Description |
|---|---|
| bool | True if the bucket exists; False otherwise. |
For the full method signature, see is_bucket_exist.
Sample code
Core usage:
result = client.is_bucket_exist(bucket="examplebucket")
print(f"Bucket exists: {result}")For a complete runnable example with credential setup and command-line argument parsing, see is_bucket_exist.py.
The following is the full sample:
import argparse
import alibabacloud_oss_v2 as oss
parser = argparse.ArgumentParser(description="Check if a specified OSS bucket exists.")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket to check for existence.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS.')
def main():
args = parser.parse_args()
# Load credentials from environment variables
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Configure the SDK with the credentials provider and region
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss.Client(cfg)
result = client.is_bucket_exist(bucket=args.bucket)
print(f'Bucket {args.bucket} exists: {result}')
if __name__ == "__main__":
main()The sample code usescn-hangzhouas the region ID. By default, a public endpoint is used. To access OSS from other Alibaba Cloud services in the same region, pass an internal endpoint using the--endpointflag. For supported regions and endpoints, see Regions and endpoints.