Os objetos armazenados no Object Storage Service (OSS) consistem em chaves, dados e metadados. Os metadados descrevem os atributos do objeto e incluem cabeçalhos HTTP padrão e metadados de usuário. Configure cabeçalhos HTTP padrão para definir políticas personalizadas de requisição HTTP, como políticas de cache e de download forçado de objetos. Configure também metadados de usuário para identificar a finalidade ou os atributos específicos de um objeto.
Observações
Este tópico usa o endpoint público da região China (Hangzhou). 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 Regiões e endpoints.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização.
Para configurar metadados de objetos, você precisa da permissão
oss:PutObject. Para consultar metadados de objetos, você precisa da permissãooss:GetObject. Para obter mais informações, consulte Conceder uma política personalizada.
Configure cabeçalhos HTTP
O código de exemplo a seguir mostra como configurar cabeçalhos HTTP para o objeto exampleobject.txt no diretório exampledir do bucket examplebucket.
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'})
Configure metadados de usuário
O código de exemplo a seguir mostra como configurar metadados de 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'})
Modifique metadados de objetos
O código de exemplo 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'})
Consulte 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, hora da última modificação e CRC64-ECMA. |
Requisições mais leves e rápidas, adequadas 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, classe de armazenamento, Content-MD5 e CRC64-ECMA. |
Mais abrangente, adequado para cenários que exigem todas as informações sobre o objeto. |
O código de exemplo 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 Gerenciar metadados de objetos.
Para obter mais informações sobre a operação de API usada para configurar metadados de objetos durante o upload simples, consulte PutObject.
Para obter mais informações sobre as operações de API usadas para consultar metadados de objetos, consulte GetObjectMeta e HeadObject.