Todos los productos
Search
Centro de documentos

Object Storage Service:Gestión de inventarios de buckets con el SDK de OSS para Python 2.0

Última actualización: Sep 24, 2026

En este tema se describe cómo crear un inventario para un bucket y cómo consultar, listar y eliminar los inventarios de un bucket mediante el SDK de Object Storage Service (OSS) para Python.

Notas

  • El código de ejemplo de este tema utiliza el ID de región cn-hangzhou, que corresponde a la región China (Hangzhou). De forma predeterminada, se usa el endpoint público para acceder a los recursos de un bucket. Si necesita acceder a los recursos del bucket desde otros servicios de Alibaba Cloud ubicados en la misma región que el bucket, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints, consulte Regions and endpoints.

  • Compruebe que cuenta con los permisos necesarios para crear, consultar, listar y eliminar inventarios de buckets. El propietario del bucket tiene estos permisos de forma predeterminada. Si no cuenta con ellos, solicite al propietario del bucket que se los otorgue.

  • Puede configurar hasta 1,000 inventarios por cada bucket.

  • El bucket de origen para el que desea configurar un inventario debe estar en la misma región que el bucket de destino donde almacenará las listas de inventario.

Ejemplos

Crear un inventario para un bucket

A continuación se muestra un ejemplo de código para crear un inventario para un bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to create an inventory for a bucket.
parser = argparse.ArgumentParser(description="put bucket inventory sample")

# Specify the command line parameters, including the required region, bucket name, endpoint, user ID, Alibaba Cloud Resource Name (ARN) of the RAM role, and inventory name.
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')
parser.add_argument('--user_id', help='User account ID.', required=True)
parser.add_argument('--arn', help='The Alibaba Cloud Resource Name (ARN) of the role that has the permissions to read all objects from the source bucket and write objects to the destination bucket. Format: `acs:ram::uid:role/rolename`.', required=True)
parser.add_argument('--inventory_id', help='The name of the inventory.', required=True)

def main():
    # Parse the command line parameters to obtain the values specified by the user.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters specified by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to create an inventory for a bucket.
    result = client.put_bucket_inventory(oss.PutBucketInventoryRequest(
            bucket=args.bucket, # The name of the bucket.
            inventory_id=args.inventory_id, # The ID of the inventory.
            inventory_configuration=oss.InventoryConfiguration(
                included_object_versions='All', # Specify that inventory lists include all versions of objects.
                optional_fields=oss.OptionalFields(
                    fields=[ # The optional fields, such as the size and last modified time of objects.
                        oss.InventoryOptionalFieldType.SIZE,
                        oss.InventoryOptionalFieldType.LAST_MODIFIED_DATE,
                    ],
                ),
                id=args.inventory_id, # The ID of the inventory.
                is_enabled=True, # Specify whether to enable the inventory feature for the bucket. In this example, the inventory feature is enabled.
                destination=oss.InventoryDestination(
                    oss_bucket_destination=oss.InventoryOSSBucketDestination(
                        format=oss. InventoryFormatType.CSV, # Specify that the output format of the inventory lists is CSV.
                        account_id=args.user_id, # The account ID of the user.
                        role_arn=args.arn, # The ARN of the RAM role, which has the permissions to read the objects in the source bucket and write objects to the destination bucket.
                        bucket=f'acs:oss:::{args.bucket}', # The name of the destination bucket.
                        prefix='aaa', # Specify the prefix contained in the names of the objects that you want to include in inventory lists.
                    ),
                ),
                schedule=oss.InventorySchedule(
                    frequency=oss. InventoryFrequencyType.DAILY, # Specify whether to generate inventory lists on a daily or weekly basis. In this example, inventory lists are generated on a daily basis.
                ),
                filter=oss.InventoryFilter(
                    lower_size_bound=1024, # Specify the minimum size of the object that you want to include in inventory lists. Unit: bytes.
                    upper_size_bound=1048576, # Specify the maximum size of the object that you want to include in inventory lists. Unit: bytes.
                    storage_class='ColdArchive', # # Specify the storage classes of objects that you want to include in inventory lists.
                    prefix='aaa', # Specify the prefix that is used to filter inventories.
                    last_modify_begin_time_stamp=1637883649, # Specify the beginning of the time range during which the object was last modified.
                    last_modify_end_time_stamp=1638347592, # Specify the end of the time range during which the object was last modified.
                ),
            ),
    ))

    # Display the HTTP status code of the operation and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
    )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.

Consultar un inventario de un bucket

El siguiente ejemplo de código muestra cómo consultar un inventario de un bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to query the inventory of a bucket.
parser = argparse.ArgumentParser(description="get bucket inventory sample")

# Specify the command line parameters, including the required region, bucket name, endpoint, and inventory ID.
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')
parser.add_argument('--inventory_id', help='The name of the inventory.', required=True)

def main():
    # Parse the command line parameters to obtain the values specified by the user.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters specified by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to query the inventory of the bucket.
    result = client.get_bucket_inventory(oss.GetBucketInventoryRequest(
            bucket=args.bucket, # The name of the bucket.
            inventory_id=args.inventory_id, # The ID of the inventory.
    ))

    # Display the HTTP status code of the operation and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' included object versions: {result.inventory_configuration.included_object_versions},'
          f' id: {result.inventory_configuration.id},'
          f' is enabled: {result.inventory_configuration.is_enabled},'
          f' account id: {result.inventory_configuration.destination.oss_bucket_destination.account_id},'
          f' role arn: {result.inventory_configuration.destination.oss_bucket_destination.role_arn},'
          f' bucket: {result.inventory_configuration.destination.oss_bucket_destination.bucket},'
          f' prefix: {result.inventory_configuration.destination.oss_bucket_destination.prefix},'
          # The following two command lines describe information about the encryption configurations. You can delete them if you do not need them.
          # f' key id: {result.inventory_configuration.destination.oss_bucket_destination.encryption.sse_kms.key_id},'
          # f' sse oss: {result.inventory_configuration.destination.oss_bucket_destination.encryption.sse_oss},'
          f' lower size bound: {result.inventory_configuration.filter.lower_size_bound},'
          f' upper size bound: {result.inventory_configuration.filter.upper_size_bound},'
          f' storage class: {result.inventory_configuration.filter.storage_class},'
          f' prefix: {result.inventory_configuration.filter.prefix},'
          f' last modify begin time stamp: {result.inventory_configuration.filter.last_modify_begin_time_stamp},'
          f' last modify end time stamp: {result.inventory_configuration.filter.last_modify_end_time_stamp},'
    )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.

Listar los inventarios de un bucket

Nota

Con una sola solicitud puede consultar hasta 100 inventarios. Si necesita consultar más de 100, envíe varias solicitudes y utilice el token devuelto en cada una como parámetro de la siguiente.

Este ejemplo de código ilustra cómo listar los inventarios de un bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to list the inventories of a bucket.
parser = argparse.ArgumentParser(description="list bucket inventory sample")

# Optional. Specify the command line parameters, including the required region, bucket name, endpoint, and inventory ID.
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')
parser.add_argument('--inventory_id', help='The name of the inventory.', required=False) # The inventory ID is optional in this scenario.

def main():
    # Parse the command line parameters to obtain the values specified by the user.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters specified by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to list the inventories of the bucket.
    result = client.list_bucket_inventory(oss.ListBucketInventoryRequest(
            bucket=args.bucket, # The name of the bucket.
    ))

    # Display the HTTP status code of the operation and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' list inventory configurations result: {result.list_inventory_configurations_result},'
          f' is truncated: {result.list_inventory_configurations_result.is_truncated},'
          f' next continuation token: {result.list_inventory_configurations_result.next_continuation_token},'
    )

    # If inventories exist, traverse and display the details of each inventory.
    if result.list_inventory_configurations_result.inventory_configurations:
        for r in result.list_inventory_configurations_result.inventory_configurations:
            print(f'result: '
                  f'included object versions: {r.included_object_versions}, '
                  f'optional fields: {r.optional_fields}, '
                  f'id: {r.id}, '
                  f'is enabled: {r.is_enabled}, '
                  f'destination: {r.destination}, '
                  f'schedule: {r.schedule}, '
                  f'filter: {r.filter}'
            )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.

Eliminar un inventario de un bucket

Para eliminar un inventario de un bucket, utilice el siguiente ejemplo de código:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to delete an inventory of a bucket.
parser = argparse.ArgumentParser(description="delete bucket inventory sample")

# Specify the command line parameters, including the required region, bucket name, endpoint, and inventory ID.
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')
parser.add_argument('--inventory_id', help='The name of the inventory.', required=True)

def main():
    # Parse the command line parameters to obtain the values specified by the user.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters specified by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to delete an inventory of a bucket.
    result = client.delete_bucket_inventory(oss.DeleteBucketInventoryRequest(
            bucket=args.bucket, # The name of the bucket.
            inventory_id=args.inventory_id, # The ID of the inventory.
    ))

    # Display the HTTP status code of the operation and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
    )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.