全部產品
Search
文件中心

Object Storage Service:儲存空間清單(Python SDK V2)

更新時間:Aug 01, 2025

本文介紹如何通過Python SDK V2添加、查看、批量列舉和刪除儲存空間(Bucket)的清單(Inventory)配置。

注意事項

  • 本文範例程式碼以華東1(杭州)的地區IDcn-hangzhou為例,預設使用外網Endpoint,如果您希望通過與OSS同地區的其他阿里雲產品訪問OSS,請使用內網Endpoint。關於OSS支援的Region與Endpoint的對應關係,請參見OSS地區和訪問網域名稱

  • 請確保您擁有調用添加、查看、列舉和刪除儲存空間清單配置的許可權。Bucket所有者預設擁有此類許可權,如果您無此類許可權,請先向Bucket所有者申請對應操作的許可權。

  • 單個Bucket最多隻能有1000條清單配置。

  • 配置清單的源Bucket與存放匯出的資訊清單檔所在的目標Bucket必須位於同一個Region。

範例程式碼

添加清單配置

以下代碼用於為某個Bucket添加清單配置:

import argparse
import alibabacloud_oss_v2 as oss

# 建立命令列參數解析器,並描述指令碼用途:設定儲存空間清單(Inventory)
parser = argparse.ArgumentParser(description="put bucket inventory sample")

# 定義命令列參數,包括必需的地區、儲存空間名稱、endpoint、使用者ID、角色ARN以及清單名稱
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():
    # 解析命令列參數,擷取使用者輸入的值
    args = parser.parse_args()

    # 從環境變數中載入訪問憑證資訊,用於身分識別驗證
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # 使用SDK預設配置建立設定物件,並設定認證提供者
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # 設定設定物件的地區屬性,根據使用者提供的命令列參數
    cfg.region = args.region

    # 如果提供了自訂endpoint,則更新設定物件中的endpoint屬性
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # 使用上述配置初始化OSS用戶端,準備與OSS互動
    client = oss.Client(cfg)

    # 發送請求以配置指定儲存空間的清單設定
    result = client.put_bucket_inventory(oss.PutBucketInventoryRequest(
            bucket=args.bucket,  # 儲存空間名
            inventory_id=args.inventory_id,  # 儲存空間清單ID
            inventory_configuration=oss.InventoryConfiguration(
                included_object_versions='All',  # 包含所有版本的對象
                optional_fields=oss.OptionalFields(
                    fields=[  # 可選欄位,如大小和最後修改日期
                        oss.InventoryOptionalFieldType.SIZE,
                        oss.InventoryOptionalFieldType.LAST_MODIFIED_DATE,
                    ],
                ),
                id=args.inventory_id,  # 儲存空間清單ID
                is_enabled=True,  # 啟用儲存空間清單
                destination=oss.InventoryDestination(
                    oss_bucket_destination=oss.InventoryOSSBucketDestination(
                        format=oss.InventoryFormatType.CSV,  # 輸出格式為CSV
                        account_id=args.user_id,  # 使用者賬戶ID
                        role_arn=args.arn,  # 角色ARN,具有讀取源儲存空間和寫入目標儲存空間的許可權
                        bucket=f'acs:oss:::{args.bucket}',  # 目標儲存空間
                        prefix='aaa',  # 資訊清單檔首碼
                    ),
                ),
                schedule=oss.InventorySchedule(
                    frequency=oss.InventoryFrequencyType.DAILY,  # 清單頻率,這裡設定為每天
                ),
                filter=oss.InventoryFilter(
                    lower_size_bound=1024,  # 對象大小下限(位元組)
                    upper_size_bound=1048576,  # 對象大小上限(位元組)
                    storage_class='ColdArchive',  # 儲存類別篩選條件
                    prefix='aaa',  # 對象首碼篩選條件
                    last_modify_begin_time_stamp=1637883649,  # 最後修改時間戳記開始範圍
                    last_modify_end_time_stamp=1638347592,  # 最後修改時間戳記結束範圍
                ),
            ),
    ))

    # 列印操作結果的狀態代碼和請求ID,以便確認請求狀態
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
    )

# 當此指令碼被直接執行時,調用main函數開始處理邏輯
if __name__ == "__main__":
    main()  # 指令碼進入點,控製程序流程從這裡開始

查看清單配置

以下代碼用於查看某個Bucket的清單配置:

import argparse
import alibabacloud_oss_v2 as oss

# 建立命令列參數解析器,並描述指令碼用途:擷取儲存空間清單配置(Inventory)
parser = argparse.ArgumentParser(description="get bucket inventory sample")

# 定義命令列參數,包括必需的地區、儲存空間名稱、endpoint以及清單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():
    # 解析命令列參數,擷取使用者輸入的值
    args = parser.parse_args()

    # 從環境變數中載入訪問憑證資訊,用於身分識別驗證
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # 使用SDK預設配置建立設定物件,並設定認證提供者
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # 設定設定物件的地區屬性,根據使用者提供的命令列參數
    cfg.region = args.region

    # 如果提供了自訂endpoint,則更新設定物件中的endpoint屬性
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # 使用上述配置初始化OSS用戶端,準備與OSS互動
    client = oss.Client(cfg)

    # 發送請求以擷取指定儲存空間的清單配置詳情
    result = client.get_bucket_inventory(oss.GetBucketInventoryRequest(
            bucket=args.bucket,  # 儲存空間名
            inventory_id=args.inventory_id,  # 清單配置ID
    ))

    # 列印操作結果的狀態代碼和請求ID,以便確認請求狀態
    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},'
          # 注釋掉的這兩行是關於加密配置的資訊,如果需要可以取消注釋
          # 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},'
    )

# 當此指令碼被直接執行時,調用main函數開始處理邏輯
if __name__ == "__main__":
    main()  # 指令碼進入點,控製程序流程從這裡開始

列舉清單配置

說明

單次請求最多可擷取100條清單配置項內容。若需擷取超過100條清單配置項,則需發送多次請求,並保留相應的Token,作為下一次請求的參數。

以下代碼用於列舉某個Bucket的清單配置:

import argparse
import alibabacloud_oss_v2 as oss

# 建立命令列參數解析器,並描述指令碼用途:列出儲存空間清單配置(Inventory)
parser = argparse.ArgumentParser(description="list bucket inventory sample")

# 定義命令列參數,包括必需的地區、儲存空間名稱、endpoint以及清單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)  # 清單ID在此情境下是可選的

def main():
    # 解析命令列參數,擷取使用者輸入的值
    args = parser.parse_args()

    # 從環境變數中載入訪問憑證資訊,用於身分識別驗證
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # 使用SDK預設配置建立設定物件,並設定認證提供者
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # 設定設定物件的地區屬性,根據使用者提供的命令列參數
    cfg.region = args.region

    # 如果提供了自訂endpoint,則更新設定物件中的endpoint屬性
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # 使用上述配置初始化OSS用戶端,準備與OSS互動
    client = oss.Client(cfg)

    # 發送請求以列出指定儲存空間的所有清單配置詳情
    result = client.list_bucket_inventory(oss.ListBucketInventoryRequest(
            bucket=args.bucket,  # 儲存空間名
    ))

    # 列印操作結果的狀態代碼和請求ID,以便確認請求狀態
    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 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}'
            )

# 當此指令碼被直接執行時,調用main函數開始處理邏輯
if __name__ == "__main__":
    main()  # 指令碼進入點,控製程序流程從這裡開始

刪除清單配置

以下代碼用於刪除某個Bucket的清單配置:

import argparse
import alibabacloud_oss_v2 as oss

# 建立命令列參數解析器,並描述指令碼用途:刪除儲存空間清單配置(Inventory)
parser = argparse.ArgumentParser(description="delete bucket inventory sample")

# 定義命令列參數,包括必需的地區、儲存空間名稱、endpoint以及清單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():
    # 解析命令列參數,擷取使用者輸入的值
    args = parser.parse_args()

    # 從環境變數中載入訪問憑證資訊,用於身分識別驗證
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # 使用SDK預設配置建立設定物件,並設定認證提供者
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # 設定設定物件的地區屬性,根據使用者提供的命令列參數
    cfg.region = args.region

    # 如果提供了自訂endpoint,則更新設定物件中的endpoint屬性
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # 使用上述配置初始化OSS用戶端,準備與OSS互動
    client = oss.Client(cfg)

    # 發送請求以刪除指定儲存空間的特定清單配置
    result = client.delete_bucket_inventory(oss.DeleteBucketInventoryRequest(
            bucket=args.bucket,  # 儲存空間名
            inventory_id=args.inventory_id,  # 清單配置ID
    ))

    # 列印操作結果的狀態代碼和請求ID,以便確認請求狀態
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
    )

# 當此指令碼被直接執行時,調用main函數開始處理邏輯
if __name__ == "__main__":
    main()  # 指令碼進入點,控製程序流程從這裡開始