OSS支持设置生命周期(Lifecycle)规则,自动删除过期的文件(Object)和碎片,或将到期的文件转储为低频或归档存储类型,从而节省存储费用。本文介绍如何管理存储空间(Bucket)的生命周期规则。

设置生命周期规则

以下代码用于为examplebucket存储空间设置生命周期规则。

# -*- coding: utf-8 -*-
import oss2
import datetime
from oss2.models import (LifecycleExpiration, LifecycleRule, 
                        BucketLifecycle,AbortMultipartUpload, 
                        TaggingRule, Tagging, StorageTransition,
                        NoncurrentVersionStorageTransition,
                        NoncurrentVersionExpiration)

# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
# yourBucketName填写Bucket名称,例如examplebucket。
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# 设置Object距其最后修改时间3天后过期。
rule1 = LifecycleRule('rule1', 'tests/',
                      status=LifecycleRule.ENABLED,
                      expiration=LifecycleExpiration(days=3))

# 设置Object过期规则,指定日期之前创建的文件过期。
rule2 = LifecycleRule('rule2', 'tests2/',
                      status=LifecycleRule.ENABLED,
expiration=LifecycleExpiration(created_before_date=datetime.date(2022, 12, 12)))

# 设置分片过期规则,分片3天后过期。
rule3 = LifecycleRule('rule3', 'tests3/',
                      status=LifecycleRule.ENABLED,
            abort_multipart_upload=AbortMultipartUpload(days=3))

# 设置分片过期规则,指定日期之前的分片过期。
rule4 = LifecycleRule('rule4', 'tests4/',
                      status=LifecycleRule.ENABLED,
                      abort_multipart_upload = AbortMultipartUpload(created_before_date=datetime.date(2022, 12, 12)))

# 设置存储类型转换规则,指定Object在其最后修改时间20天之后转为低频访问类型,在其最后修改时间30天之后转为归档类型。
rule5 = LifecycleRule('rule5', 'tests5/',
                      status=LifecycleRule.ENABLED,
                      storage_transitions=[StorageTransition(days=20,storage_class=oss2.BUCKET_STORAGE_CLASS_IA),
                            StorageTransition(days=30,storage_class=oss2.BUCKET_STORAGE_CLASS_ARCHIVE)])

# 设置匹配的标签。
tagging_rule = TaggingRule()
tagging_rule.add('key1', 'value1')
tagging_rule.add('key2', 'value2')
tagging = Tagging(tagging_rule)

# 设置存储类型转换规则,指定Object在其最后修改时间超过365天后转为ARCHIVE类型。 
# rule6与以上几个规则不同的是它指定了匹配的标签,同时拥有key1=value1,key2=value2两个标签的object才会匹配此规则。
rule6 = LifecycleRule('rule6', 'tests6/',
                      status=LifecycleRule.ENABLED,
                      storage_transitions=[StorageTransition(created_before_date=datetime.date(2022, 12, 12),storage_class=oss2.BUCKET_STORAGE_CLASS_IA)],
                      tagging = tagging)

# rule7针对版本控制状态下的Bucket。
# 设置Object在其最后修改时间365天之后自动转为ARCHIVE类型。
# 设置自动移除过期删除标记。
# 设置非当前版本Object 12天后转为IA类型。
# 设置非当前版本Object 20天后转为ARCHIVE类型。
# 设置非当前版本Object 30天后删除。
rule7 = LifecycleRule('rule7', 'tests7/',
              status=LifecycleRule.ENABLED,
              storage_transitions=[StorageTransition(days=365, storage_class=oss2.BUCKET_STORAGE_CLASS_ARCHIVE)], 
              expiration=LifecycleExpiration(expired_detete_marker=True),
              noncurrent_version_sotrage_transitions = 
                    [NoncurrentVersionStorageTransition(12, oss2.BUCKET_STORAGE_CLASS_IA),
                     NoncurrentVersionStorageTransition(20, oss2.BUCKET_STORAGE_CLASS_ARCHIVE)],
              noncurrent_version_expiration = NoncurrentVersionExpiration(30))

lifecycle = BucketLifecycle([rule1, rule2, rule3, rule4, rule5, rule6, rule7])

bucket.put_bucket_lifecycle(lifecycle)

查看生命周期规则

以下代码用于查看examplebucket存储空间的生命周期规则。

# -*- coding: utf-8 -*-
import oss2
# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
# yourBucketName填写Bucket名称,例如examplebucket。
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# 查看生命周期规则。
lifecycle = bucket.get_bucket_lifecycle()

for rule in lifecycle.rules:
    print('==========')
    print('id:', rule.id)
    print('prefix:', rule.prefix)
    print('status', rule.status)

    if rule.tagging is not None:
        print('tagging:', rule.tagging)

    if rule.abort_multipart_upload is not None:
        if rule.abort_multipart_upload.days is not None:
            print('abort_multipart_upload days:', rule.abort_multipart_upload.days)
        else:
            print('abort_multipart_upload created_before_date:', rule.abort_multipart_upload.created_before_date)

    if rule.expiration is not None:
        if rule.expiration.days is not None:
            print('expiration days:', rule.expiration.days)
        elif rule.expiration.expired_detete_marker is not None:
            print('expiration expired_detete_marker:', rule.expiration.expired_detete_marker)
        elif rule.expiration.created_before_date is not None:
            print('expiration created_before_date:', rule.expiration.created_before_date)

    if len(rule.storage_transitions) > 0: 
        storage_info = ''
        for storage_rule in rule.storage_transitions:
            if storage_rule.days is not None:
                storage_info += 'days={0}, storage_class={1} *** '.format(
                        storage_rule.days, storage_rule.storage_class)
            else:
                storage_info += 'created_before_date={0}, storage_class={1} *** '.format(
                        storage_rule.created_before_date, storage_rule.storage_class) 
        print('storage_transitions:', storage_info)

    if len(rule.noncurrent_version_sotrage_transitions) > 0:
        noncurrent_storage_info = ''
        for storage_rule in rule.noncurrent_version_sotrage_transitions:
            noncurrent_storage_info += 'days={0}, storage_class={1} *** '.format(
                storage_rule.noncurrent_days, storage_rule.storage_class)
        print('noncurrent_version_sotrage_transitions:', noncurrent_storage_info)

    if rule.noncurrent_version_expiration is not None:
        print('noncurrent_version_expiration days:', rule.noncurrent_version_expiration.noncurrent_days)

清空生命周期规则

以下代码用于清空examplebucket存储空间的生命周期规则。

# -*- coding: utf-8 -*-
import oss2

# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
# yourBucketName填写Bucket名称,例如examplebucket。
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# 清空生命周期规则。
bucket.delete_bucket_lifecycle()

# 再次查看生命周期规则会抛出异常。
try:
    lifecycle = bucket.get_bucket_lifecycle()
except oss2.exceptions.NoSuchLifecycle:
    print('lifecycle is not configured')
            

相关文档