Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciar metadados de objetos usando OSS SDK for Python 1.0

Última atualização: Sep 24, 2026

Os objetos armazenados no Object Storage Service (OSS) são compostos por chaves, dados e metadados de objetos. Os metadados descrevem os atributos do objeto e se dividem em dois tipos: cabeçalhos HTTP padrão e metadados do usuário. Ao configurar cabeçalhos HTTP padrão, é possível criar políticas de requisição personalizadas, como políticas de cache e de download forçado de objetos. Além disso, configure metadados do usuário para identificar as finalidades ou características de um objeto.

Observações

  • Neste tópico, o endpoint público da região China (Hangzhou) é usado como exemplo. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Initialization.

  • Para configurar metadados de objetos, é necessário ter a permissão oss:PutObject. Para consultar metadados de objetos, é necessário ter a permissão oss:GetObject. Para obter mais informações, consulte Grant a custom policy.

Configurar cabeçalhos HTTP

O exemplo de código a seguir mostra como configurar cabeçalhos HTTP para o objeto exampleobject.txt no diretório exampledir do bucket examplebucket.

Nota

Para obter mais informações sobre cabeçalhos HTTP, consulte RFC 2616.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
object_name = 'exampledir/exampleobject.txt'
# Specify the string that you want to upload. 
content = '{"age": 1}'
# Configure HTTP headers. For example, set the Content-Type header to 'application/json; charset=utf-8'. 
bucket.put_object(object_name, content, headers={'Content-Type': 'application/json; charset=utf-8'})

Configurar metadados do usuário

O exemplo de código a seguir mostra como configurar metadados do usuário para o objeto exampleobject.txt no diretório exampledir do bucket examplebucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
object_name = 'exampledir/exampleobject.txt'
# Specify the string that you want to upload. 
content = 'a novel'
# Configure the user metadata. User metadata is configured by specifying custom headers prefixed with x-oss-meta-. Sample header: x-oss-meta-author. Sample value: O. Henry.  
bucket.put_object(object_name, content, headers={'x-oss-meta-author': 'O. Henry', 'Content-Type': 'application/json; charset=utf-8'})

Modificar metadados de objetos

O exemplo de código a seguir mostra como modificar os metadados do objeto exampleobject.txt no diretório exampledir do bucket examplebucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
object_name = 'exampledir/exampleobject.txt'
# Modify the object metadata. 
bucket.update_object_meta(object_name, {'x-oss-meta-author': 'O. Henry'})
# Each time you use the bucket.update_object_meta method, the user metadata is updated. 
bucket.update_object_meta(object_name, {'Content-Type': 'text/plain'})

Consultar metadados de objetos

Use os métodos fornecidos pelo OSS SDK for Python para consultar metadados de objetos.

Método

Descrição

Observações

get_object_meta

Consulta parte dos metadados do objeto, incluindo ETag, tamanho, data da última modificação e CRC64-ECMA.

Leve e com requisições mais rápidas; indicado para cenários em que apenas parte das informações básicas precisa ser recuperada.

head_object

Consulta todos os metadados do objeto, incluindo Content-Length, Content-Type, storage-class, Content-MD5 e CRC64-ECMA.

Mais completo; recomendado para cenários em que todas as informações do objeto são necessárias.

O exemplo de código a seguir mostra como consultar os metadados do objeto exampleobject.txt no diretório exampledir do bucket examplebucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
object_name = 'exampledir/exampleobject.txt'

# Query part of the object metadata by using the get_object_meta method. 
simplifiedmeta = bucket.get_object_meta(object_name)
# Display part of the object metadata.
print("Last-Modified: " + simplifiedmeta.headers['Last-Modified'])  # Query the last modified time of the object. 
print("Content-Length: " + simplifiedmeta.headers['Content-Length'])  # Query the size of the object. 
print("ETag: " + simplifiedmeta.headers['ETag'])  # Query the ETag of the object.
# Query the object metadata, including the last access time of the object, after you enable access tracking. You can use only OSS SDK for Python 2.16.1 and later to query the last access time of objects.
# print(simplifiedmeta.headers['x-oss-last-access-time'])

# Query all object metadata by using the head_object method. 
objectmeta = bucket.head_object(object_name)
# In this example, only part of the object metadata is displayed. You can add code lines to display other object metadata. 
# Display part of the object metadata.
print("Content-Type: " + objectmeta.headers['Content-Type'])  # Query the MIME type of the object.
print("Content-MD5: " + objectmeta.headers['Content-MD5'])  # Query the MD5 hash of the object.
print("x-oss-storage-class: " + objectmeta.headers['x-oss-storage-class'])  # Query the storage class of the object.
print("x-oss-hash-crc64ecma: " + objectmeta.headers['x-oss-hash-crc64ecma'])  # Query the CRC64-ECMA of the object.

# Output all headers.
# Uncomment the following code to output all headers.
# print("\n all headers:")
# for key, value in objectmeta.headers.items():
#     print(f"{key}: {value}")

Referências

  • Para obter mais informações sobre metadados de objetos, consulte Manage object metadata.

  • Para obter mais informações sobre a operação de API que pode ser chamada para configurar metadados de objetos durante o upload simples, consulte PutObject.

  • Para obter mais informações sobre as operações de API que podem ser chamadas para consultar metadados de objetos, consulte GetObjectMeta e HeadObject.