Tous les produits
Search
Centre de documentation

Object Storage Service:Gérer les métadonnées d'objet à l'aide du SDK OSS pour Python 1.0

Dernière mise à jour :Sep 24, 2026

Les objets stockés dans Object Storage Service (OSS) se composent d'une clé, de données et de métadonnées. Les métadonnées décrivent les attributs de l'objet. Elles incluent des en-têtes HTTP standard et des métadonnées utilisateur. En configurant les en-têtes HTTP standard, vous pouvez définir des stratégies de requête HTTP personnalisées, telles que la mise en cache ou le téléchargement forcé des objets. Vous pouvez également configurer des métadonnées utilisateur pour identifier l'usage ou les attributs d'un objet.

Notes

  • Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez Régions et endpoints.

  • Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Initialisation.

  • Pour configurer les métadonnées d'objet, vous devez disposer de l'autorisation oss:PutObject. Pour interroger les métadonnées d'objet, vous devez disposer de l'autorisation oss:GetObject. Pour plus d'informations, consultez Accorder une politique personnalisée.

Configurer les en-têtes HTTP

L'exemple de code suivant montre comment configurer les en-têtes HTTP pour l'objet exampleobject.txt situé dans le répertoire exampledir du bucket examplebucket.

Remarque

Pour plus d'informations sur les en-têtes HTTP, consultez 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'})

Configurer les métadonnées utilisateur

L'exemple de code suivant montre comment configurer les métadonnées utilisateur pour l'objet exampleobject.txt situé dans le répertoire exampledir du 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'})

Modifier les métadonnées d'objet

L'exemple de code suivant montre comment modifier les métadonnées de l'objet exampleobject.txt situé dans le répertoire exampledir du 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'})

Interroger les métadonnées d'objet

Utilisez les méthodes fournies par le SDK OSS pour Python afin d'interroger les métadonnées d'objet.

Méthode

Description

Remarques

get_object_meta

Interroge une partie des métadonnées de l'objet, y compris l'ETag, la taille, la date de dernière modification et le CRC64-ECMA.

Légère et rapide, adaptée aux scénarios où seule une partie des informations de base est nécessaire.

head_object

Interroge toutes les métadonnées de l'objet, y compris Content-Length, Content-Type, storage-class, Content-MD5 et CRC64-ECMA.

Plus complète, adaptée aux scénarios où toutes les informations sur l'objet sont requises.

L'exemple de code suivant montre comment interroger les métadonnées de l'objet exampleobject.txt situé dans le répertoire exampledir du 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}")

Références

  • Pour plus d'informations sur les métadonnées d'objet, consultez Gérer les métadonnées d'objet.

  • Pour plus d'informations sur l'opération API permettant de configurer les métadonnées d'objet lors d'un chargement simple, consultez PutObject.

  • Pour plus d'informations sur les opérations API permettant d'interroger les métadonnées d'objet, consultez GetObjectMeta et HeadObject.