Este tópico descreve como criar um inventário para um bucket e como consultar, listar e excluir os inventários de um bucket usando o Object Storage Service (OSS) SDK for Python.
Observações
O código de exemplo neste tópico usa o ID da região
cn-hangzhouda região China (Hangzhou). Por padrão, o SDK usa o endpoint público para acessar recursos em um bucket. Para acessar recursos no bucket a partir de outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para obter mais informações sobre regiões e endpoints, consulte Regions and endpoints.Certifique-se de ter as permissões para criar, consultar, listar e excluir inventários de buckets. Por padrão, o proprietário do bucket tem as permissões para executar essas operações. Se você não tiver essas permissões, entre em contato com o proprietário do bucket para solicitá-las.
É possível configurar até 1.000 inventários por bucket.
O bucket de origem do inventário deve estar na mesma região do bucket de destino, onde as listas de inventário serão armazenadas.
Exemplos
Criar um inventário para um bucket
O código de exemplo a seguir mostra como criar um inventário para um 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 um inventário de um bucket
O exemplo de código abaixo demonstra como consultar um inventário de um 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 os inventários de um bucket
É possível consultar até 100 inventários em uma única requisição. Para consultar mais de 100 inventários, envie múltiplas requisições e use o token retornado em cada uma como parâmetro para a próxima.
O código a seguir exemplifica como listar os inventários de um 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.
Excluir um inventário de um bucket
Veja o exemplo de código abaixo para excluir um inventário de um 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 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.