全部產品
Search
文件中心

Object Storage Service:管理檔案中繼資料(Python SDK V2)

更新時間:Jul 31, 2025

本文介紹如何使用OSS Python SDK設定和擷取檔案中繼資料。

注意事項

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

  • 本文以從環境變數讀取存取憑證為例。如何配置訪問憑證,請參見配置訪問憑證

  • 要設定檔案中繼資料,您必須具有oss:PutObject許可權;要擷取檔案中繼資料,您必須具有oss:GetObject許可權。具體操作,請參見為RAM使用者授予自訂的權限原則

上傳檔案時設定中繼資料

上傳檔案時設定中繼資料

以下代碼使用上傳檔案(PutObject)為例設定中繼資料,包括設定檔案到期時間、設定檔案為公用讀取、設定自訂中繼資料來標識檔案的用途或屬性等。其他上傳類對象介面都支援設定中繼資料,且設定方式與PutObject方法一致。

import argparse
import requests
import alibabacloud_oss_v2 as oss

from alibabacloud_oss_v2.models import (
    PutObjectRequest, GetObjectRequest, DeleteObjectRequest,
    ListObjectsRequest, PutBucketRequest, GetBucketAclRequest
    # 其他您需要的請求類...
)

# 建立命令列參數解析器
parser = argparse.ArgumentParser(description="put object sample")
# 添加命令列參數 --region,表示儲存空間所在的地區,必需參數
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# 添加命令列參數 --bucket,表示儲存空間的名稱,必需參數
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# 添加命令列參數 --endpoint,表示其他服務可用來訪問OSS的網域名稱,非必需參數
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# 添加命令列參數 --key,表示對象的名稱,必需參數
parser.add_argument('--key', help='The name of the object.', 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用戶端
    client = oss.Client(cfg)

    # 定義要上傳的字串內容
    text_string = "Hello, OSS!"
    data = text_string.encode('utf-8')  # 將字串編碼為UTF-8位元組串

    # 執行上傳對象的請求,指定儲存空間名稱、對象名稱和資料內容
    result = client.put_object(oss.PutObjectRequest(
        bucket=args.bucket,
        key=args.key,
        body=data,
        metadata={
            'key1': 'value1',
            'key2': 'value2'
        }
    ))

    # 輸出請求的結果狀態代碼、請求ID、內容MD5、ETag、CRC64校正碼和版本ID,用於檢查請求是否成功
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
    )

if __name__ == "__main__":
    main()  # 指令碼入口,當檔案被直接運行時調用main函數

擷取檔案中繼資料

使用HeadObject方法擷取對象的所有中繼資料

您可以通過以下代碼使用HeadObject方法擷取指定Object的所有中繼資料。

import argparse
import alibabacloud_oss_v2 as oss

# 建立命令列參數解析器,並描述指令碼用途:擷取對象頭部資訊樣本
parser = argparse.ArgumentParser(description="head object sample")

# 添加命令列參數 --region,表示儲存空間所在的地區,必需參數
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# 添加命令列參數 --bucket,表示儲存空間的名稱,必需參數
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# 添加命令列參數 --endpoint,表示其他服務可用來訪問OSS的網域名稱,非必需參數
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# 添加命令列參數 --key,表示對象的名稱,必需參數
parser.add_argument('--key', help='The name of the object.', required=True)

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

    # 從環境變數中載入訪問OSS所需的認證資訊,用於身分識別驗證
    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.head_object(oss.HeadObjectRequest(
        bucket=args.bucket,           # 指定儲存空間名稱
        key=args.key,                 # 指定對象名稱
    ))

    # 列印操作結果的各種中繼資料資訊
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content length: {result.content_length},'
          f' content type: {result.content_type},'
          f' etag: {result.etag},'
          f' last modified: {result.last_modified},'
          f' content md5: {result.content_md5},'
          f' cache control: {result.cache_control},'
          f' content disposition: {result.content_disposition},'
          f' content encoding: {result.content_encoding},'
          f' expires: {result.expires},'
          f' hash crc64: {result.hash_crc64},'
          f' storage class: {result.storage_class},'
          f' object type: {result.object_type},'
          f' version id: {result.version_id},'
          f' tagging count: {result.tagging_count},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
          f' server side encryption key id: {result.server_side_encryption_key_id},'
          f' next append position: {result.next_append_position},'
          f' expiration: {result.expiration},'
          f' restore: {result.restore},'
          f' process status: {result.process_status},'
          f' request charged: {result.request_charged},'
          f' allow origin: {result.allow_origin},'
          f' allow methods: {result.allow_methods},'
          f' allow age: {result.allow_age},'
          f' allow headers: {result.allow_headers},'
          f' expose headers: {result.expose_headers},'
          )

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

使用GetObjectMeta方法擷取對象的部分中繼資料

說明

使用GetObjectMeta方法僅可以擷取部分的對象中繼資料,包括:返回內容的長度(ContentLength)、實體標籤(ETag)、返回的對象最後一次被修改的時間(LastModified)、對象最後一次被訪問的時間(LastAccessTime)、對象的版本ID(VersionId)、對象的 64 位元 CRC 值(HashCRC64)。

您可以通過以下代碼使用GetObjectMeta方法擷取指定對象的部分中繼資料。

import argparse
import alibabacloud_oss_v2 as oss

# 建立命令列參數解析器,並描述指令碼用途:擷取對象中繼資料樣本
parser = argparse.ArgumentParser(description="get object meta sample")

# 添加命令列參數 --region,表示儲存空間所在的地區,必需參數
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# 添加命令列參數 --bucket,表示儲存空間的名稱,必需參數
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# 添加命令列參數 --endpoint,表示其他服務可用來訪問OSS的網域名稱,非必需參數
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# 添加命令列參數 --key,表示對象的名稱,必需參數
parser.add_argument('--key', help='The name of the object.', required=True)

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

    # 從環境變數中載入訪問OSS所需的認證資訊,用於身分識別驗證
    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_object_meta(oss.GetObjectMetaRequest(
        bucket=args.bucket,           # 指定儲存空間名稱
        key=args.key,                 # 指定對象名稱
    ))

    # 列印操作結果的狀態代碼、請求ID、內容長度、ETag、最後修改時間、最後訪問時間、版本ID以及雜湊CRC64等資訊,以便確認請求狀態
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content length: {result.content_length},'
          f' etag: {result.etag},'
          f' last modified: {result.last_modified},'
          f' last access time: {result.last_access_time},'
          f' version id: {result.version_id},'
          f' hash crc64: {result.hash_crc64},'
          )

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

修改已有檔案的中繼資料

使用CopyObject方法修改對象中繼資料

您可以通過以下代碼使用CopyObject方法拷貝來源物件時設定目標對象的中繼資料。

import argparse
import alibabacloud_oss_v2 as oss

# 建立命令列參數解析器
parser = argparse.ArgumentParser(description="copy object sample")

# 添加命令列參數 --region,表示儲存空間所在的地區,必需參數
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# 添加命令列參數 --bucket,表示目標儲存空間的名稱,必需參數
parser.add_argument('--bucket', help='The name of the destination bucket.', required=True)
# 添加命令列參數 --endpoint,表示其他服務可用來訪問OSS的網域名稱,非必需參數
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# 添加命令列參數 --key,表示目標對象的名稱,必需參數
parser.add_argument('--key', help='The name of the destination object.', required=True)
# 添加命令列參數 --source_key,表示來源物件的名稱,必需參數
parser.add_argument('--source_key', help='The name of the source object.', required=True)
# 添加命令列參數 --source_bucket,表示源儲存空間的名稱,必需參數
parser.add_argument('--source_bucket', help='The name of the source bucket.', 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用戶端
    client = oss.Client(cfg)

    # 執行複製對象的請求
    result = client.copy_object(oss.CopyObjectRequest(
        bucket=args.bucket,  # 指定目標儲存空間名稱
        key=args.key,  # 指定目標對象鍵名
        source_key=args.source_key,  # 指定來源物件鍵名
        source_bucket=args.source_bucket,  # 指定源儲存空間名稱
        metadata={'key1': 'value1', 'key2': 'value2'}, # 指定中繼資料
        metadata_directive='REPLACE', # 指定中繼資料處理方式
    ))

    # 輸出複製對象的結果資訊
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' version id: {result.version_id},'
          f' hash crc64: {result.hash_crc64},'
          f' source version id: {result.source_version_id},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
          f' last modified: {result.last_modified},'
          f' etag: {result.etag},'
    )

# 當此指令碼被直接運行時,調用main函數
if __name__ == "__main__":
    main()  # 指令碼入口,當檔案被直接運行時調用main函數

使用拷貝管理器Copier.Copy方法修改對象中繼資料

您可以通過以下代碼使用拷貝管理器Copier.Copy方法拷貝來源物件時設定目標對象的中繼資料,包括使用新的中繼資料替換原來的中繼資料,清除原來的中繼資料或者更新指定的部分中繼資料,在拷貝對象完成後可以選擇是否刪除來源物件。

import argparse
import alibabacloud_oss_v2 as oss

# 建立命令列參數解析器
parser = argparse.ArgumentParser(description="copier sample")

# 添加命令列參數:region(必填),指定Bucket所在的地區
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# 添加命令列參數:bucket(必填),指定目標Bucket名稱
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# 添加命令列參數:endpoint(可選),指定OSS的訪問網域名稱
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# 添加命令列參數:key(必填),指定目標對象的名稱
parser.add_argument('--key', help='The name of the object.', required=True)

# 添加命令列參數:source_key(必填),指定來源物件的名稱
parser.add_argument('--source_key', help='The name of the source address for object.', required=True)

# 添加命令列參數:source_bucket(必填),指定源Bucket的名稱
parser.add_argument('--source_bucket', help='The name of the source address for bucket.', required=True)


def main():
    # 解析命令列參數
    args = parser.parse_args()

    # 從環境變數中載入憑證資訊
    # 使用EnvironmentVariableCredentialsProvider從環境變數中讀取Access Key ID和Access Key Secret
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # 使用SDK的預設配置
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider  # 設定憑證提供者
    cfg.region = args.region  # 設定Bucket所在的地區
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint  # 如果提供了endpoint,則設定自訂訪問網域名稱

    # 建立OSS用戶端執行個體
    client = oss.Client(cfg)

    # 建立Copier執行個體並執行對象複製操作
    copier = client.copier()

    # 執行對象複製操作
    result = copier.copy(
        oss.CopyObjectRequest(
            bucket=args.bucket,          # 目標Bucket名稱
            key=args.key,                # 目標對象名稱
            source_bucket=args.source_bucket,  # 源Bucket名稱
            source_key=args.source_key,  # 來源物件名稱
            metadata={'key1': 'value1', 'key2': 'value2'}, # 設定目標對象的中繼資料
            metadata_directive="REPLACE",   # 指定中繼資料處理方式
        )
    )

    # 列印複製結果
    # 使用vars(result)將結果對象轉換為字典格式並列印
    print(vars(result))


if __name__ == "__main__":
    main()