edit-icon download-icon

Manage buckets

Last Updated: Dec 21, 2017

A bucket is a namespace on OSS and a management entity for billing, access control, logging, and other advanced features.

View all buckets

You can use oss2.BucketIterator to traverse all the buckets:

  1. # -*- coding: utf-8 -*-
  2. import oss2
  3. auth = oss2.Auth ('Your AccessKeyID', 'Your AccessKeySecret')
  4. service = oss2.Service(auth, 'Your endpoint')
  5. print([b.name for b in oss2.BucketIterator(service)])

Specifically, the oss2.Service is used to access “OSS service”- related classes. Currently, it is only used to list the user’s buckets.

Create a bucket

You can create a new bucket in a specified region by specifying an endpoint and a bucket name:

  1. bucket = oss2.Bucket (auth, 'Your endpoint', 'your bucket name')
  2. bucket.create_bucket()

For example, when you set the endpoint to http://oss-cn-beijing.aliyuncs.com, you can create a bucket in the Beijing region.

For information about endpoints, regions, and their mapping relationships and bucket naming conventions, see OSS Basic Concepts.

You can specify the bucket ACL when creating a bucket. For example, you can use the following code to create a public-read bucket:

  1. bucket.create_bucket(oss2.BUCKET_ACL_PUBLIC_READ)

Delete a bucket

You can use the following code to delete an empty bucket.

  1. try:
  2. bucket.delete_bucket()
  3. except oss2.exceptions.BucketNotEmpty:
  4. print('bucket is not empty.')
  5. except oss2.exceptions.NoSuchBucket:
  6. print('bucket does not exist')

If the bucket to be deleted is not empty (an object or a part in the bucket is being uploaded), the bucket cannot be deleted, and the SDK throws the BucketNotEmpty exception. If the bucket to be deleted does not exist, the SDK throws the NoSuchBucket exception.


  • Once a bucket is deleted, the name of the bucket may be applied for by other users.
  • If a bucket is not empty, you can list and delete objects in the bucket (terminate multipart upload if it is in progress) to clear the bucket, and then delete the bucket.

View the access permissions of the bucket

  1. print(bucket.get_bucket_acl().acl)

Set the access permissions of a bucket

The following code sets the access permission of a bucket to private:

  1. bucket.put_bucket_acl(oss2.BUCKET_ACL_PRIVATE)
Thank you! We've received your feedback.