Los objetos almacenados en Object Storage Service (OSS) se componen de claves, datos y metadatos. Los metadatos describen los atributos del objeto e incluyen encabezados HTTP estándar y metadatos de usuario. Al configurar los encabezados HTTP estándar, puede crear políticas personalizadas de solicitudes HTTP, como las de caché o descarga forzada de objetos. También es posible configurar los metadatos de usuario de un objeto para identificar sus propósitos o atributos.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.
Para configurar los metadatos de un objeto, se requiere el permiso
oss:PutObject. Para consultarlos, se requiere el permisooss:GetObject. Para obtener más información, consulte Grant a custom policy.
Configuración de encabezados HTTP
A continuación se muestra un ejemplo de código para configurar los encabezados HTTP del objeto exampleobject.txt. Este archivo se encuentra en el directorio exampledir del bucket examplebucket.
Para obtener más información sobre los encabezados 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'})
Configuración de metadatos de usuario
A continuación se muestra un ejemplo de código para configurar los metadatos de usuario del objeto exampleobject.txt. Este archivo se ubica en el directorio exampledir del 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'})
Modificación de metadatos de objetos
A continuación se muestra un ejemplo de código para modificar los metadatos del objeto exampleobject.txt. Dicho objeto se encuentra en el directorio exampledir del 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'})
Consulta de metadatos de objetos
Puede utilizar los métodos proporcionados por OSS SDK for Python para consultar los metadatos de los objetos.
|
Método |
Descripción |
Observaciones |
|
get_object_meta |
Consulta una parte de los metadatos del objeto, como ETag, tamaño, hora de última modificación y CRC64-ECMA. |
Genera solicitudes ligeras y rápidas. Recomendado cuando solo se necesita recuperar información básica parcial. |
|
head_object |
Consulta todos los metadatos del objeto, incluidos Content-Length, Content-Type, storage-class, Content-MD5 y CRC64-ECMA. |
Ofrece información completa. Más indicado para escenarios donde se requieren todos los detalles del objeto. |
A continuación se muestra un ejemplo de código para consultar los metadatos del objeto exampleobject.txt. Este archivo está ubicado en el directorio exampledir del 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}")
Referencias
Para obtener más información sobre los metadatos de objetos, consulte Manage object metadata.
Para conocer la operación de API que permite configurar los metadatos durante una carga simple, consulte PutObject.
Si desea consultar las operaciones de API disponibles para obtener los metadatos de un objeto, consulte GetObjectMeta y HeadObject.