Cette rubrique explique comment créer un inventaire pour un compartiment, ainsi que comment interroger, répertorier et supprimer les inventaires d'un compartiment à l'aide du SDK Object Storage Service (OSS) pour Python.
Notes
L'exemple de code de cette rubrique utilise l'ID de région
cn-hangzhoude la région Chine (Hangzhou). Par défaut, le point de terminaison public permet d'accéder aux ressources d'un compartiment. Pour accéder aux ressources du compartiment depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison, consultez la page Régions et points de terminaison.Assurez-vous de disposer des autorisations nécessaires pour créer, interroger, répertorier et supprimer les inventaires de compartiments. Par défaut, le propriétaire du compartiment est autorisé à effectuer ces opérations. Si vous ne possédez pas ces autorisations, contactez le propriétaire du compartiment pour qu'il vous les accorde.
Vous pouvez configurer jusqu'à 1 000 inventaires par compartiment.
Le compartiment source pour lequel vous configurez un inventaire doit se trouver dans la même région que le compartiment de destination où seront stockées les listes d'inventaire.
Exemples
Créer un inventaire pour un compartiment
L'exemple de code suivant montre comment créer un inventaire pour un compartiment :
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.
Interroger un inventaire de compartiment
L'exemple de code suivant montre comment interroger un inventaire de compartiment :
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.
Répertorier les inventaires d'un compartiment
Une seule requête permet d'interroger jusqu'à 100 inventaires. Pour en interroger davantage, envoyez plusieurs requêtes en utilisant le jeton renvoyé par chaque requête comme paramètre pour la suivante.
L'exemple de code suivant montre comment répertorier les inventaires d'un compartiment :
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.
Supprimer un inventaire de compartiment
L'exemple de code suivant montre comment supprimer un inventaire de compartiment :
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.