When versioning is enabled for a bucket, you can restore an object to any of its previous versions if the object is accidentally overwritten or deleted. Versioning applies to all objects in a bucket.
Prerequisites
Before you begin, ensure that you have:
An OSS bucket
The
oss:PutBucketVersioningpermission to enable or suspend versioning, or theoss:GetBucketVersioningpermission to query the versioning state. For details, see Grant a custom access policy to a RAM user
Usage notes
The sample code uses the China (Hangzhou) region (
cn-hangzhou) and the public endpoint by default. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint instead. For a full list of regions and endpoints, see OSS regions and endpoints.
Enable versioning
The following code enables versioning for a bucket by calling put_bucket_versioning with status set to Enabled.
import argparse
import alibabacloud_oss_v2 as oss
parser = argparse.ArgumentParser(description="put bucket versioning sample")
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.', 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()
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.put_bucket_versioning(oss.PutBucketVersioningRequest(
bucket=args.bucket,
versioning_configuration=oss.VersioningConfiguration(
status='Enabled'
)
))
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
)
if __name__ == "__main__":
main()For the complete sample code, see put_bucket_version.py.