Todos los productos
Search
Centro de documentos

Object Storage Service:Uso de etiquetas de objetos para la gestión del ciclo de vida (OSS SDK for Python 1.0)

Última actualización: Sep 22, 2026

Configure reglas de ciclo de vida para objetos con prefijos o etiquetas específicos. También puede especificar una combinación de prefijos y etiquetas como condiciones de las reglas de ciclo de vida.

Nota

Si configura condiciones de etiqueta, la regla se aplica únicamente a los objetos que cumplen con la clave y el valor de etiqueta indicados. Cuando una regla incluye un prefijo y varias etiquetas de objeto, esta se aplica solo a los objetos que coinciden tanto con el prefijo como con las condiciones de etiqueta.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.

Especificar etiquetas en una regla de ciclo de vida

A continuación se muestra un ejemplo de código para especificar etiquetas en una regla de ciclo de vida:

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

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 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. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Specify that objects expire three days after they are last modified. 
# Specify the name of the expiration rule and the prefix to match the objects. 
rule1 = LifecycleRule('rule1', 'tests/',
                      # Enable the expiration rule. 
                      status=LifecycleRule.ENABLED,
                      # Specify that objects expire three days after they are last modified. 
                      expiration=LifecycleExpiration(days=3))

# Specify that the objects last modified before the specified date expire. 
# Specify the name of the expiration rule and the prefix to match the objects. 
rule2 = LifecycleRule('rule2', 'logging-',
                      # Disable the expiration rule. 
                      status=LifecycleRule.DISABLED,
                      # Specify that the objects last modified before the specified date expire. 
                      expiration=LifecycleExpiration(created_before_date=datetime.date(2018, 12, 12)))

# Specify that parts expire three days after they are last modified. 
rule3 = LifecycleRule('rule3', 'tests1/',
                      status=LifecycleRule.ENABLED,
                      abort_multipart_upload=AbortMultipartUpload(days=3))

# Specify that the parts last modified before the specified date expire. 
rule4 = LifecycleRule('rule4', 'logging1-',
                      status=LifecycleRule.DISABLED,
                      abort_multipart_upload = AbortMultipartUpload(created_before_date=datetime.date(2018, 12, 12)))

# Configure tags to match objects. 
tagging_rule = TaggingRule()
tagging_rule.add('key1', 'value1')
tagging_rule.add('key2', 'value2')
tagging = Tagging(tagging_rule)

# Configure the rule to convert the storage class of an object. Specify that the storage class of an object is converted to Archive 365 days after the object is last modified.  
# Tags that match objects are specified in rule5. The rule applies only to objects that match tag conditions of key1=value1 and key2=value2. 
rule5 = LifecycleRule('rule5', 'logging2-',
                      status=LifecycleRule.ENABLED,
                      storage_transitions=[StorageTransition(days=365, storage_class=oss2.BUCKET_STORAGE_CLASS_ARCHIVE)],
                      tagging = tagging)

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

bucket.put_bucket_lifecycle(lifecycle)

Consultar las etiquetas configuradas en una regla de ciclo de vida

A continuación se muestra un ejemplo de código para consultar las etiquetas configuradas en una regla de ciclo de vida:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 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. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Query the lifecycle rules. 
lifecycle = bucket.get_bucket_lifecycle()

for rule in lifecycle.rules:
    # Query the part expiration rules. 
    if rule.abort_multipart_upload is not None:
        print('id={0}, prefix={1}, tagging={2}, status={3}, days={4}, created_before_date={5}'
                .format(rule.id, rule.prefix, rule.tagging, rule.status,
                    rule.abort_multipart_upload.days,
                    rule.abort_multipart_upload.created_before_date))

    # Query the object expiration rules. 
    if rule.expiration is not None:
        print('id={0}, prefix={1}, tagging={2}, status={3}, days={4}, created_before_date={5}'
                .format(rule.id, rule.prefix, rule.tagging, rule.status,
                    rule.expiration.days,
                    rule.expiration.created_before_date))
    # Query the rules that convert the storage class of an object. 
    if len(rule.storage_transitions) > 0: 
        storage_trans_info = ''
        for storage_rule in rule.storage_transitions:
            storage_trans_info += 'days={0}, created_before_date={1}, storage_class={2} **** '.format(
                storage_rule.days, storage_rule.created_before_date, storage_rule.storage_class)

        print('id={0}, prefix={1}, tagging={2}, status={3},, StorageTransition={4}'
                .format(rule.id, rule.prefix, rule.tagging, rule.status, storage_trans_info))

Referencias

  • Para consultar el código de ejemplo completo que se utiliza para gestionar reglas de ciclo de vida, visite GitHub.

  • Para obtener más información sobre la operación de API que permite configurar reglas de ciclo de vida, consulte PutBucketLifecycle.

  • Para obtener más información sobre la operación de API que permite consultar reglas de ciclo de vida, consulte GetBucketLifecycle.