Este tópico descreve como fazer upload de objetos para um bucket com versionamento usando upload simples, upload por anexação e upload multipart.
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 mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).
Este tópico demonstra como criar 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 fazer upload de um objeto, você precisa da permissão
oss:PutObject. Para mais informações, consulte Conceder uma política personalizada.
Upload simples
Ao enviar um objeto para um bucket com versionamento habilitado, o OSS gera um ID de versão exclusivo e o inclui na resposta como valor do cabeçalho x-oss-version-id. Se você fizer upload em um bucket com versionamento suspenso, o OSS atribuirá ao objeto um ID de versão nulo. Caso já exista um objeto com o mesmo nome, o novo upload sobrescreverá o existente. Assim, cada objeto terá apenas uma versão com ID nulo.
O código de exemplo a seguir mostra como usar o upload simples para enviar um objeto a um bucket com versionamento habilitado:
# -*- 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)
Upload por anexação
Em buckets com versionamento habilitado, a operação AppendObject só pode ser executada na versão atual de um objeto anexável.
Ao executar a operação AppendObject na versão atual de um objeto anexável, o OSS não gera uma versão anterior para esse objeto.
Quando as operações PutObject ou DeleteObject são aplicadas a um objeto cuja versão atual é anexável, o OSS armazena o objeto anexável como uma versão anterior e impede novas anexações.
Não é possível executar a operação AppendObject em objetos cuja versão atual não seja anexável, como objetos normais ou marcadores de exclusão.
O código de exemplo a seguir mostra como fazer upload de um objeto usando upload por anexação:
# -*- 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')
Upload multipart
Ao chamar a operação CompleteMultipartUpload para concluir uma tarefa de upload multipart em um bucket com versionamento habilitado, o OSS gera um ID de versão exclusivo para o objeto e o retorna como valor do cabeçalho x-oss-version-id na resposta.
O código de exemplo a seguir mostra como fazer upload de um objeto para um bucket com versionamento habilitado usando upload multipart:
# -*- 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()
Referências
Para mais informações sobre a operação de API de upload simples, consulte PutObject.
Para mais informações sobre a operação de API de upload por anexação, consulte AppendObject.
Para mais informações sobre a operação de API para concluir um upload multipart, consulte CompleteMultipartUpload.