Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciar metadados de objetos com o OSS SDK for Python 2.0

Última atualização: Jul 03, 2026

Este tópico descreve como configurar e consultar metadados de objetos usando o OSS SDK for Python.

Observações

  • Os códigos de exemplo deste tópico usam o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o acesso aos recursos em um bucket ocorre via endpoint público. Para acessar esses recursos por meio de outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Neste tópico, as credenciais de acesso são obtidas a partir de variáveis de ambiente. Para saber mais sobre como configurar essas credenciais, consulte Configurar credenciais de acesso.

  • Para configurar metadados de objetos, é necessária a permissão oss:PutObject. Para consultar metadados, é necessária a permissão oss:GetObject. Para mais informações, consulte Conceder uma política personalizada.

Configurar metadados durante o upload de objetos

Configurar metadados durante o upload de objetos

O exemplo de código a seguir faz o upload de um objeto usando PutObject e define cabeçalhos de metadados, como tempo de expiração, lista de controle de acesso (ACL) e metadados personalizados. Aplique o mesmo procedimento de configuração ao usar outras operações de API de upload.

import argparse
import requests
import alibabacloud_oss_v2 as oss

from alibabacloud_oss_v2.models import (
    PutObjectRequest, GetObjectRequest, DeleteObjectRequest,
    ListObjectsRequest, PutBucketRequest, GetBucketAclRequest
    # Any other classes that you need.
)

# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="put object sample")
# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter to indicate the name of the object. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    args = parser.parse_args()  # Parse the command-line parameters.

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

    # Load the default configuration of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Specify the region in which the bucket is located.
    cfg.region = args.region
    # If an endpoint is provided, specify the endpoint in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configuration to create an OSSClient instance.
    client = oss.Client(cfg)

    # Specify the string that you want to upload.
    text_string = "Hello, OSS!"
    data = text_string.encode('utf-8')  # Encode the string by using the UTF-8 encoding.

    # Execute the request to upload the object.
    result = client.put_object(oss.PutObjectRequest(
        bucket=args.bucket,
        key=args.key,
        body=data,
        metadata={
            'key1': 'value1',
            'key2': 'value2'
        }
    ))

    # Display the HTTP status code, request ID, MD5 hash, ETag, CRC-64 value, and object version ID to check whether the request is successful.
    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() # The entry point of the script. When the script is directly run, the main function is called.

Consultar metadados de objetos

Consultar todos os metadados de um objeto com o método HeadObject

O exemplo de código a seguir consulta todos os metadados de um objeto usando o método HeadObject:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser and describe the purpose of the script.
parser = argparse.ArgumentParser(description="head object sample")

# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter to indicate the name of the object. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command-line parameters.
    args = parser.parse_args()

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

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

    # Set the region attribute of the cfg object to the region in the parser.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configuration to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Send a request to get the headers of the object.
    result = client.head_object(oss.HeadObjectRequest(
        bucket=args.bucket,           # Specify the bucket name.
        key=args.key,                 # Specify the object key.
    ))

    # Print the result details.
    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},'
          )

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

Usar o método GetObjectMeta para consultar metadados parciais de um objeto

Nota

O método GetObjectMeta permite consultar apenas parte dos metadados do objeto, incluindo comprimento do conteúdo retornado (ContentLength), tag de entidade (ETag), hora da última modificação (LastModified), hora do último acesso (LastAccessTime), ID da versão (VersionId) e hash CRC-64 (HashCRC64).

O exemplo de código a seguir consulta metadados parciais de um objeto usando o método GetObjectMeta:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser and describe the purpose of the script.
parser = argparse.ArgumentParser(description="get object meta sample")

# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter to indicate the name of the object. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command-line parameters.
    args = parser.parse_args()

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

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

    # Set the region attribute of the cfg object to the region in the parser.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configuration to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Send a request to get the metadata of the object.
    result = client.get_object_meta(oss.GetObjectMetaRequest(
        bucket=args.bucket,           # Specify the bucket name.
        key=args.key,                 # Specify the object key.
    ))

    # Display the HTTP status code, request ID, content length, ETag, last modification time, and last access time, object version ID, and CRC64 hash to check whether the request is successful.
    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},'
          )

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

Modificar metadados de um objeto existente

Usar o método **CopyObject** para modificar metadados de objetos

O exemplo de código a seguir modifica os metadados de um objeto usando o método CopyObject:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="copy object sample")

# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the destination bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the destination bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter to indicate the name of the destination object. This parameter is required.
parser.add_argument('--key', help='The name of the destination object.', required=True)
# Specify the --source_key to indicate the name of the source object. This parameter is required.
parser.add_argument('--source_key', help='The name of the source object.', required=True)
# Specify the --source_bucket parameter to indicate the name of the source bucket. This parameter is required.
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)

def main():
    # Parse the command-line parameters.
    args = parser.parse_args()

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

    # Load the default configuration of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located.
    cfg.region = args.region

    # If an endpoint is provided, specify the endpoint in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configuration to create an OSSClient instance.
    client = oss.Client(cfg)

    # Copy the source object.
    result = client.copy_object(oss.CopyObjectRequest(
        bucket=args.bucket,           # Specify the name of the destination bucket.
        key=args.key,  # Specify the key of the destination object.
        source_key=args.source_key,  # Specify the key of the source object.
        source_bucket=args.source_bucket,  # Specify the name of the source bucket.
        metadata={'key1': 'value1', 'key2': 'value2'}, # Specify the metadata.
        metadata_directive='REPLACE', # Specify the metadata directive.
    ))

    # Display the details of the operation result.
    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},'
    )

# Call the main function when the script is directly run.
if __name__ == "__main__":
    main() # The entry point of the script. When the script is directly run, the main function is called.

Usar **Copier.Copy** para modificar metadados de objetos

Use Copier.Copy para copiar um objeto de origem e definir metadados para o objeto de destino. É possível substituir todos os metadados originais por novos valores, remover metadados existentes ou atualizar apenas cabeçalhos específicos. Também é possível excluir o objeto de origem após a conclusão da cópia.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="copier sample")

# Specify the region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Specify the bucket parameter to indicate the name of the destination bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Specify the endpoint parameter to indicate the OSS endpoint that is used to access OSS. This parameter is optional
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# Specify the key parameter to indicate the name of the destination object. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)

# Specify the source_key parameter to indicate the name of the source object. This parameter is required.
parser.add_argument('--source_key', help='The name of the source address for object.', required=True)

# Specify the source_bucket parameter to indicate the name of the source bucket. This parameter is required.
parser.add_argument('--source_bucket', help='The name of the source address for bucket.', required=True)

def main():
    # Parse the command-line parameters.
    args = parser.parse_args()

    # Obtain access credentials from environment variables.
    # Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration of the SDK.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider  # Specify the credential provider.
    cfg.region = args.region  # Specify the region in which the bucket is located.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint  # If an endpoint is provided, specify the endpoint in the configuration object.

    # Create an OSSClient instance.
    client = oss.Client(cfg)

    # Create a copier instance.
    copier = client.copier()

    # Copy the source object.
    result = copier.copy(
        oss.CopyObjectRequest(
            bucket=args.bucket,          # The name of the destination bucket.
            key=args.key,                # The name of the destination object.
            source_bucket=args.source_bucket,  # The name of the source bucket.
            source_key=args.source_key,  # The key of the source object.
            metadata={'key1': 'value1', 'key2': 'value2'}, # The metadata of the destination object.
            metadata_directive="REPLACE",   # Specify the metadata directive.
        )
    )

    # Display the object copy result.
    # Return a dictionary of attributes of the result object by using vars() and display the dictionary.
    print(vars(result))

if __name__ == "__main__":
    main()