Todos os produtos
Search
Central de documentação

Object Storage Service:Cópia multipart usando o OSS SDK for Python 2.0

Última atualização: Sep 24, 2026

Este tópico descreve como usar o método UploadPartCopy do OSS SDK for Python 2.0 para copiar partes de um objeto em um bucket de origem e montá-las em um novo objeto completo em um bucket de destino. Os buckets de origem e de destino podem ser iguais ou diferentes, mas devem estar na mesma região.

Observações de uso

  • O código de exemplo neste tópico usa o ID da região cn-hangzhou, da região China (Hangzhou). Por padrão, use um endpoint público para acessar recursos em um bucket. Se quiser acessar recursos no bucket a partir de qualquer outro serviço da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para obter mais informações sobre as regiões e os endpoints compatíveis com o OSS, consulte Regions and endpoints.

  • Para copiar um objeto, você precisa de permissões de leitura no objeto de origem e de leitura e gravação no bucket de destino.

  • Os buckets de origem e de destino devem estar na mesma região. Por exemplo, objetos em um bucket na região China (Hangzhou) não podem ser copiados para um bucket na região China (Qingdao).

  • Verifique se não há políticas de retenção configuradas para os buckets de origem e de destino. Caso contrário, o OSS retornará a seguinte mensagem de erro: The object you specified is immutable.

Método

upload_part_copy(request: UploadPartCopyRequest, **kwargs) → UploadPartCopyResult

Parâmetros da requisição

Parâmetro

Tipo

Descrição

request

UploadPartCopyRequest

Os parâmetros da requisição. Para obter mais informações, consulte UploadPartCopyRequest

Parâmetros de resposta

Tipo

Descrição

UploadPartCopyResult

O valor de retorno. Para obter mais informações, consulte UploadPartCopyResult

Para ver a definição completa do método de cópia multipart, consulte upload_part_copy.

Processo de cópia multipart

Para fazer upload de um arquivo local usando multipart upload, execute as seguintes etapas:

  1. Inicie uma tarefa de multipart upload.

    Use o método client.initiate_multipart_upload para obter um ID de upload exclusivo no OSS.

  2. Carregue as partes.

    Use o método client.upload_part_copy para obter um ID de upload exclusivo no OSS.

    Nota
    • Para as partes carregadas ao executar uma tarefa de multipart upload com um ID de upload específico, os números das partes identificam suas posições relativas em um objeto. Se você carregar uma parte e reutilizar o número dela para carregar outra, a nova parte substituirá a original.

    • O OSS inclui o hash MD5 dos dados da parte no cabeçalho ETag e o retorna para o usuário.

    • O OSS calcula o hash MD5 das partes carregadas e o compara com o hash MD5 calculado pelo OSS SDK for Harmony. Se os dois hashes forem diferentes, o OSS retornará o código de erro InvalidDigest.

  3. Conclua a tarefa de multipart upload.

    Combine as partes carregadas em um objeto com o método client.complete_multipart_upload.

Código de exemplo

O exemplo de código a seguir mostra como copiar um objeto de um bucket de origem para um bucket de destino por meio de cópia multipart e combinar as partes em um objeto completo:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line argument parser and describe the purpose of the script: synchronous multipart copy and upload sample
parser = argparse.ArgumentParser(description="upload part copy synchronously sample")

# Add the --region command line parameter, which indicates the region where the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command line parameter, which indicates the name of the destination bucket to which the object is to be uploaded. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command line parameter, which indicates the domain name that other services can use to access OSS. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command line parameter, which indicates the key of the destination object in OSS. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Add the --source_bucket command line parameter, which indicates the name of the bucket where the source object is located. This parameter is required.
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)
# Add the --source_key command line parameter, which indicates the key of the source object in OSS. This parameter is required.
parser.add_argument('--source_key', help='The name of the source object.', required=True)

def main():
    # Parse the parameters provided on the command line to obtain the values entered by the user.
    args = parser.parse_args()

    # Load the authentication information required to access OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client and prepare for interaction with OSS.
    client = oss.Client(cfg)

    # Obtain the metadata of the source object.
    result_meta = client.get_object_meta(oss.GetObjectMetaRequest(
        bucket=args.source_bucket,
        key=args.source_key,
    ))

    # Initialize a multipart upload request and return an upload ID to identify the process.
    result = client.initiate_multipart_upload(oss.InitiateMultipartUploadRequest(
        bucket=args.bucket,
        key=args.key,
    ))

    # Define the size of each part. In this example, the size is set to 1 MB.
    part_size = 1024 * 1024
    total_size = result_meta.content_length  # The total size of the source file.
    part_number = 1  # The part number starts from 1.
    upload_parts = []  # Used to store the information of uploaded parts.
    offset = 0  # The current byte offset.

    # Loop until all data is uploaded.
    while offset < total_size:
        num_to_upload = min(part_size, total_size - offset)  # Calculate the amount of data to be uploaded this time.
        end = offset + num_to_upload - 1  # Determine the end position.

        # Perform the actual multipart copy and upload operation.
        up_result = client.upload_part_copy(oss.UploadPartCopyRequest(
            bucket=args.bucket,
            key=args.key,
            upload_id=result.upload_id,
            part_number=part_number,
            source_bucket=args.source_bucket,
            source_key=args.source_key,
            source_range=f'bytes={offset}-{end}',  # Specify the range in the source object.
        ))

        # Print the status information of the uploaded part.
        print(f'status code: {up_result.status_code},'
              f' request id: {up_result.request_id},'
              f' part number: {part_number},'
              f' last modified: {up_result.last_modified},'
              f' etag: {up_result.etag},'
              f' source version id: {up_result.source_version_id}'
        )

        # Record the information of the successfully uploaded part.
        upload_parts.append(oss.UploadPart(part_number=part_number, etag=up_result.etag))
        offset += num_to_upload  # Update the offset.
        part_number += 1  # Update the part number.

    # Sort all uploaded parts by part number.
    parts = sorted(upload_parts, key=lambda p: p.part_number)

    # Send a request to the OSS service to complete the multipart upload.
    result = client.complete_multipart_upload(oss.CompleteMultipartUploadRequest(
        bucket=args.bucket,
        key=args.key,
        upload_id=result.upload_id,
        complete_multipart_upload=oss.CompleteMultipartUpload(
            parts=parts
        )
    ))

    # Print the detailed results after the upload is complete.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' bucket: {result.bucket},'
          f' key: {result.key},'
          f' location: {result.location},'
          f' etag: {result.etag},'
          f' encoding type: {result.encoding_type},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id}'
    )

# When this script is directly executed, call the main function to start processing the logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts from here.

Referência