Tous les produits
Search
Centre de documentation

Object Storage Service:Télécharger des objets (OSS SDK for Python 1.0)

Dernière mise à jour :Sep 22, 2026

Cette rubrique explique comment télécharger des objets dans un bucket versionné en utilisant les méthodes de téléchargement simple, par ajout et multipartie.

Notes

  • Dans cette rubrique, le point de terminaison public de la région Chine (Hangzhou) est utilisé. Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région qu'OSS, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Dans cette rubrique, les identifiants d'accès sont obtenus à partir des variables d'environnement. Pour savoir comment configurer les identifiants d'accès, consultez Configurer les identifiants d'accès à l'aide d'OSS SDK for Python 1.0.

  • 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 avec des identifiants du Security Token Service (STS), consultez Initialisation.

  • Pour télécharger un objet, vous devez disposer de l'autorisation oss:PutObject. Pour plus d'informations, consultez Accorder une politique personnalisée.

Téléchargement simple

Si vous lancez une requête pour télécharger un objet dans un bucket pour lequel le versioning est activé, OSS génère un ID de version unique pour l'objet téléchargé et inclut cet ID de version dans la réponse en tant que valeur de l'en-tête x-oss-version-id. Si vous téléchargez un objet dans un bucket pour lequel le versioning est suspendu, OSS génère un ID de version nul pour l'objet. Si l'objet que vous téléchargez porte le même nom qu'un objet existant, l'objet existant est écrasé par l'objet téléchargé. Ainsi, chaque objet ne possède qu'une seule version dont l'ID de version est nul.

L'exemple de code suivant montre comment utiliser le téléchargement simple pour télécharger un objet dans un bucket pour lequel le versioning est activé :

# -*- 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)

# Upload the object. 
result = bucket.put_object('yourObjectName', 'content of object')
# Display the returned HTTP status code. 
print('http response code: {0}'.format(result.status))
# Display the version ID of the uploaded object. 
print('put object version:', result.versionid)

Téléchargement par ajout

Dans un bucket pour lequel le versioning est activé, l'opération AppendObject ne peut être effectuée que sur la version actuelle d'un objet pouvant faire l'objet d'ajouts.

Remarque
  • Lorsque vous effectuez l'opération AppendObject sur la version actuelle d'un objet pouvant faire l'objet d'ajouts, OSS ne génère pas de version précédente pour l'objet.

  • Lorsque vous effectuez l'opération PutObject ou DeleteObject sur un objet dont la version actuelle est un objet pouvant faire l'objet d'ajouts, OSS stocke l'objet en tant que version précédente et empêche tout ajout ultérieur à l'objet.

  • L'opération AppendObject ne peut pas être effectuée sur un objet dont la version actuelle n'est pas un objet pouvant faire l'objet d'ajouts, comme un objet normal ou un marqueur de suppression.

L'exemple de code suivant montre comment télécharger un objet en utilisant le téléchargement par ajout :

# -*- 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)

# Set the position from which the first append operation starts to 0. 
result = bucket.append_object('yourObjectName', 0, 'content of first append')
# Display the version ID of the object that is appended. 
print('append object versionid:', result.versionid)
# If you have appended content to the object, you can obtain the position from which the operation starts this time from the next_position field in the response returned by the last operation or by using the bucket.head_object method. 
bucket.append_object('yourObjectName', result.next_position, 'content of second append')

Téléchargement multipartie

Si vous appelez l'opération CompleteMultipartUpload pour finaliser la tâche de téléchargement multipartie d'un objet dans un bucket pour lequel le versioning est activé, OSS génère un ID de version unique pour l'objet et renvoie cet ID de version en tant que valeur de l'en-tête x-oss-version-id dans la réponse.

L'exemple de code suivant montre comment télécharger un objet dans un bucket pour lequel le versioning est activé en utilisant le téléchargement multipartie :

# -*- coding: utf-8 -*-
import os
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2 import SizedFileAdapter, determine_part_size
from oss2.models import PartInfo
# 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)

key = 'yourObjectName'
filename = 'yourLocalFile'

total_size = os.path.getsize(filename)
# Specify the determine_part_size method to determine the part size. 
part_size = determine_part_size(total_size, preferred_size=100 * 1024)

# Initiate a multipart upload task. 
upload_id = bucket.init_multipart_upload(key).upload_id
parts = []

# Upload the parts. 
with open(filename, 'rb') as fileobj:
    part_number = 1
    offset = 0
    while offset < total_size:
        num_to_upload = min(part_size, total_size - offset)
    # The SizedFileAdapter(fileobj, size) method generates a new object and recalculates the position from which the append operation starts. 
        result = bucket.upload_part(key, upload_id, part_number,
                                    SizedFileAdapter(fileobj, num_to_upload))
        parts.append(PartInfo(part_number, result.etag))

        offset += num_to_upload
        part_number += 1

# Complete the multipart upload task. 
result = bucket.complete_multipart_upload(key, upload_id, parts)
# Display the version ID of the uploaded object, which is returned in the response.
print('result.versionid:', result.versionid)

# Verify the result of the multipart upload task. 
with open(filename, 'rb') as fileobj:
    assert bucket.get_object(key).read() == fileobj.read()

Références

  • Pour plus d'informations sur l'opération API que vous pouvez appeler pour effectuer un téléchargement simple, consultez PutObject.

  • Pour plus d'informations sur l'opération API que vous pouvez appeler pour effectuer un téléchargement par ajout, consultez AppendObject.

  • Pour plus d'informations sur l'opération API que vous pouvez appeler pour finaliser un téléchargement multipartie, consultez CompleteMultipartUpload.