Todos los productos
Search
Centro de documentos

Object Storage Service:Gestión del ciclo de vida con OSS SDK for Python 2.0

Última actualización: Sep 24, 2026

Este tema describe cómo usar el SDK de Python V2 para gestionar las reglas de ciclo de vida de un bucket.

Contexto

En OSS, no todos los datos cargados requieren acceso frecuente. Sin embargo, por motivos de cumplimiento normativo o archivado, algunos datos deben conservarse como almacenamiento en frío. Según sus necesidades de negocio, seleccione una de a continuación opciones:

  1. Reglas de ciclo de vida basadas en la última fecha de modificación: si los datos llevan mucho tiempo sin modificarse y ya no es necesario conservarlos, utilice este tipo de regla. Así podrá eliminar los datos por lotes o cambiar su clase de almacenamiento a una más fría para liberar espacio.

  2. Reglas de ciclo de vida basadas en la última fecha de acceso: habilite este tipo de regla para que OSS supervise automáticamente los patrones de acceso a los datos. El servicio identifica los datos que no se han consultado durante mucho tiempo y los convierte a una clase de almacenamiento en frío más rentable. Este proceso implementa la clasificación automática de almacenamiento y reduce los costos.

Precauciones

  • Antes de configurar una regla de ciclo de vida basada en la última fecha de modificación o de acceso, asegúrese de comprender bien esta función. Para obtener más información, consulte Lifecycle rules based on the last modified time y Lifecycle rules based on the last access time.

  • El código de ejemplo de este tema utiliza la región China (Hangzhou), cuyo identificador es cn-hangzhou. De forma predeterminada, se usa un endpoint público. Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región, utilice un endpoint interno. Para conocer las regiones y los endpoints compatibles con OSS, consulte OSS regions and endpoints.

  • Para establecer una regla de ciclo de vida, necesita el permiso oss:PutBucketLifecycle. Para consultar las reglas de ciclo de vida, requiere el permiso oss:GetBucketLifecycle. Para eliminar todas las reglas de ciclo de vida, debe contar con el permiso oss:DeleteBucketLifecycle. Para obtener más información sobre cómo otorgar estos permisos, consulte Grant custom permissions to a RAM user.

Establecer reglas de ciclo de vida

A continuación se muestran ejemplos de código para establecer reglas de ciclo de vida basadas en la última fecha de modificación y en la última fecha de acceso. Si desea modificar una o varias reglas después de configurarlas, consulte How do I modify the configurations of one or more lifecycle rules?.

Cambiar la clase de almacenamiento de los objetos según una política basada en la última fecha de modificación

El siguiente ejemplo de código muestra cómo establecer una regla de ciclo de vida en un bucket para cambiar la clase de almacenamiento de los objetos según su última fecha de modificación.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user-entered parameters.
parser = argparse.ArgumentParser(description="put bucket lifecycle sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
  # Parse command-line arguments.
  args = parser.parse_args()

  # Load credentials (AccessKey ID and AccessKey secret) from environment variables.
  credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

  # Load the default configurations of the SDK.
  cfg = oss.config.load_default()

  # Set the credentials provider.
  cfg.credentials_provider = credentials_provider

  # Set the region where the bucket is located.
  cfg.region = args.region

  # If a custom endpoint is provided by the user, set it in the configuration.
  if args.endpoint is not None:
    cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
  client = oss.Client(cfg)

  result = client.put_bucket_lifecycle(oss.PutBucketLifecycleRequest(
    bucket=args.bucket,
    lifecycle_configuration=oss.LifecycleConfiguration(
      rules=[oss.LifecycleRule(
        # Specify lifecycle rule rule1. In this rule, objects that have the prefix foo/ and the tag k1:v1 are converted to the Infrequent Access (IA) storage class 30 days after they are last modified.
        id='rule1',
        status='Enabled',
        prefix='foo/',
        transitions=[oss.LifecycleRuleTransition(
          days=30,
          storage_class=oss.StorageClassType.IA,
          is_access_time=False, # Set to false, which indicates that the policy is based on the last modified time.
        )],
        tags=[oss.Tag(
          key='k1',
          value='v1',
        )],
      ), oss.LifecycleRule(
        # Specify lifecycle rule rule2. In this rule, for objects that have the prefix dir/, delete markers are automatically deleted if the objects are in a versioning-enabled bucket and have only delete markers. Non-current versions of objects expire and are deleted after 30 days. Non-current versions of objects are converted to the IA storage class after 10 days.
        id='rule2',
        status='Enabled',
        prefix='dir/',
        expiration=oss.LifecycleRuleExpiration(
          expired_object_delete_marker=True
        ),
        noncurrent_version_expiration=oss.NoncurrentVersionExpiration(
          noncurrent_days=30,
        ),
        noncurrent_version_transitions=[oss.NoncurrentVersionTransition(
          noncurrent_days=10,
          storage_class=oss.StorageClassType.IA,
          is_access_time=False,
        )],
      )]
    ),
  ))

  # Print the status code and request ID of the operation.
  print(f'status code: {result.status_code}, '  # The HTTP status code, which indicates whether the request is successful.
        f'request id: {result.request_id}')    # The request ID, which is used to track request logs and for debugging.

if __name__ == "__main__":
  # The program entry point that calls the main function to execute the logic.
  main()

Cambiar la clase de almacenamiento de objetos sin prefijo ni etiqueta específicos según una política basada en la última fecha de modificación

El siguiente ejemplo de código muestra cómo convertir los objetos de un bucket a la clase de almacenamiento Infrequent Access 30 días después de su última modificación. Esta regla aplica a los objetos que cumplen con los requisitos de tamaño especificados, que no tienen el prefijo log y que carecen de una etiqueta con la clave key1 y el valor value1.

import argparse
import datetime
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user-entered parameters.
parser = argparse.ArgumentParser(description="put bucket lifecycle sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load credentials (AccessKey ID and AccessKey secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Set the credentials provider.
    cfg.credentials_provider = credentials_provider

    # Set the region where the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided by the user, set it in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
    client = oss.Client(cfg)

    result = client.put_bucket_lifecycle(oss.PutBucketLifecycleRequest(
            bucket=args.bucket,
            lifecycle_configuration=oss.LifecycleConfiguration(
                rules=[oss.LifecycleRule(
                    # Specify lifecycle rule rule1. In this rule, objects that have the prefix logs/ and a size between 500 bytes and 1,000 bytes are converted to the Infrequent Access (IA) storage class 30 days after they are last modified. This rule does not apply to objects that also have the prefix logs/log and the tag key:key1 and value:value1.
                    id='rule1',
                    status='Enabled',
                    prefix='logs/',
                    transitions=[oss.LifecycleRuleTransition(
                        days=30,
                        storage_class=oss.StorageClassType.IA,
                        is_access_time=False, # Set to false, which indicates that the policy is based on the last modified time.
                    )],
                    filter=oss.LifecycleRuleFilter(
                        object_size_greater_than=500,
                        object_size_less_than=1000,
                        filter_not=[oss.LifecycleRuleNot(
                            prefix='logs/log',
                            tag={
                               'key': 'key1',
                                'value': 'value1',
                            },
                        )],
                    )
                )]
            ),
    ))

    # Print the status code and request ID of the operation.
    print(f'status code: {result.status_code}, '  # The HTTP status code, which indicates whether the request is successful.
          f'request id: {result.request_id}')    # The request ID, which is used to track request logs and for debugging.

if __name__ == "__main__":
    # The program entry point that calls the main function to execute the logic.
    main()

Cambiar la clase de almacenamiento de los objetos según una política basada en la última fecha de acceso

El siguiente ejemplo de código muestra cómo establecer una regla de ciclo de vida en un bucket para cambiar la clase de almacenamiento de los objetos según su última fecha de acceso.

import argparse
import datetime
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="put bucket lifecycle 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()
  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_lifecycle(oss.PutBucketLifecycleRequest(
    bucket=args.bucket,
    lifecycle_configuration=oss.LifecycleConfiguration(
      rules=[
        oss.LifecycleRule(
          id='rule1',
          status='Enabled',
          prefix='data/',
          transitions=[oss.LifecycleRuleTransition(
            days=200,
            storage_class=oss.StorageClassType.IA,
            is_access_time=True,
            return_to_std_when_visit=False
          )]
        ),
        oss.LifecycleRule(
          id='rule2',
          status='Enabled',
          prefix='log/',
          transitions=[
            oss.LifecycleRuleTransition(
              days=120,
              storage_class=oss.StorageClassType.IA,
              is_access_time=True,
              return_to_std_when_visit=False
            ),
            oss.LifecycleRuleTransition(
              days=250,
              storage_class=oss.StorageClassType.ARCHIVE
              # If is_access_time is not set, the rule is based on the last modified time by default.
            )
          ]
        )
      ]
    )
  ))

  print(f'status code: {result.status_code}, '
        f'request id: {result.request_id}')

if __name__ == "__main__":
  main()

Consultar reglas de ciclo de vida

El siguiente ejemplo de código muestra cómo consultar las reglas de ciclo de vida.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user-entered parameters.
parser = argparse.ArgumentParser(description="get bucket lifecycle sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load credentials (AccessKey ID and AccessKey secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Set the credentials provider.
    cfg.credentials_provider = credentials_provider

    # Set the region where the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided by the user, set it in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
    client = oss.Client(cfg)

    # Call the get_bucket_lifecycle method to obtain the lifecycle rules of the bucket.
    result = client.get_bucket_lifecycle(
        oss.GetBucketLifecycleRequest(
            bucket=args.bucket,  # Specify the name of the destination bucket.
        )
    )

    # Print the status code and request ID of the operation.
    print(f'status code: {result.status_code}, '  # The HTTP status code, which indicates whether the request is successful.
          f'request id: {result.request_id}')    # The request ID, which is used to track request logs and for debugging.

    # If the returned collection of lifecycle rules contains rules, print the details of each rule one by one.
    if result.lifecycle_configuration.rules:  # Check whether lifecycle rules exist.
        for r in result.lifecycle_configuration.rules:  # Traverse all rules.
            print(f'rule: {r}')  # Print the content of each rule.

if __name__ == "__main__":
    # The program entry point that calls the main function to execute the logic.
    main()

Eliminar todas las reglas de ciclo de vida

El siguiente ejemplo de código muestra cómo eliminar todas las reglas de ciclo de vida de un bucket llamado examplebucket. Si desea eliminar una o varias reglas de ciclo de vida, consulte How do I delete one or more lifecycle rules?.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user-entered parameters.
parser = argparse.ArgumentParser(description="delete bucket lifecycle sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load credentials (AccessKey ID and AccessKey secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Set the credentials provider.
    cfg.credentials_provider = credentials_provider

    # Set the region where the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided by the user, set it in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
    client = oss.Client(cfg)

    # Call the delete_bucket_lifecycle method to delete the lifecycle rules of the bucket.
    result = client.delete_bucket_lifecycle(
        oss.DeleteBucketLifecycleRequest(
            bucket=args.bucket,  # Specify the name of the destination bucket.
        )
    )

    # Print the status code and request ID of the operation.
    print(f'status code: {result.status_code}, '  # The HTTP status code, which indicates whether the request is successful.
          f'request id: {result.request_id}')    # The request ID, which is used to track request logs and for debugging.

if __name__ == "__main__":
    # The program entry point that calls the main function to execute the logic.
    main()

Referencias

  • Para ver el código de ejemplo completo sobre cómo establecer una regla de ciclo de vida, consulte put_bucket_lifecycle.py.

  • Para revisar el código de ejemplo completo sobre cómo consultar reglas de ciclo de vida, consulte get_bucket_lifecycle.py.

  • Si necesita el código de ejemplo completo para eliminar todas las reglas de ciclo de vida, consulte delete_bucket_lifecycle.py.