Todos los productos
Search
Centro de documentos

Object Storage Service:Carga de objetos (OSS SDK for Python 1.0)

Última actualización: Sep 22, 2026

En este tema se describe cómo cargar objetos en un bucket con control de versiones mediante carga simple, carga por adición y carga multiparte.

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 que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Las credenciales de acceso se obtienen a partir de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials using OSS SDK for Python 1.0.

  • 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 cargar un objeto, debe contar con el permiso oss:PutObject. Para obtener más información, consulte Grant a custom policy.

Carga simple

Si inicia una solicitud para cargar un objeto en un bucket con el control de versiones habilitado, OSS genera un identificador de versión único para el objeto cargado e incluye dicho identificador en la respuesta como valor del encabezado x-oss-version-id. Si carga un objeto en un bucket con el control de versiones suspendido, OSS asigna al objeto un identificador de versión null. Cuando el objeto que carga tiene el mismo nombre que uno ya existente, el nuevo objeto sobrescribe al anterior. De esta manera, cada objeto conserva únicamente una versión cuyo identificador es null.

A continuación se muestra un ejemplo de código para cargar un objeto en un bucket con control de versiones habilitado mediante carga simple:

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

Carga por adición

En un bucket con control de versiones habilitado, la operación AppendObject solo se puede ejecutar sobre la versión actual de un objeto anexable.

Nota
  • Cuando ejecuta la operación AppendObject sobre la versión actual de un objeto anexable, OSS no genera una versión anterior para ese objeto.

  • Si ejecuta la operación PutObject o DeleteObject sobre un objeto cuya versión actual es anexable, OSS almacena dicho objeto como una versión anterior e impide que se le agregue más contenido.

  • La operación AppendObject no se puede ejecutar sobre un objeto cuya versión actual no sea anexable, como un objeto normal o un marcador de eliminación.

A continuación se muestra un ejemplo de código para cargar un objeto mediante carga por adición:

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

Carga multiparte

Si llama a la operación CompleteMultipartUpload para finalizar la tarea de carga multiparte de un objeto en un bucket con control de versiones habilitado, OSS genera un identificador de versión único para el objeto. Este identificador se devuelve en la respuesta como valor del encabezado x-oss-version-id.

A continuación se muestra un ejemplo de código para cargar un objeto en un bucket con control de versiones habilitado mediante carga multiparte:

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

Referencias

  • Para obtener más información sobre la operación de API que permite realizar una carga simple, consulte PutObject.

  • Para obtener más información sobre la operación de API que permite realizar una carga por adición, consulte AppendObject.

  • Para obtener más información sobre la operación de API que permite finalizar una carga multiparte, consulte CompleteMultipartUpload.