Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciador de cópia de arquivos (Python SDK V2)

Última atualização: Sep 25, 2026

Este tópico descreve como usar o módulo Copier do OSS SDK for Python V2 para copiar arquivos em transferências de arquivos grandes.

Observações

  • O código de exemplo neste tópico usa o ID de região cn-hangzhou para a região China (Hangzhou). Por padrão, é usado um endpoint público. Ao acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre o mapeamento entre regiões e endpoints do OSS, consulte Regions and endpoints.

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

  • A cópia entre regiões não é suportada. Por exemplo, não é possível copiar um objeto de um bucket na região China (Hangzhou) para um bucket na região China (Qingdao).

  • Ao copiar um objeto, verifique se nenhuma política de retenção está configurada nos buckets de origem e de destino. Caso contrário, o erro The object you specified is immutable. é retornado.

Definição de método

Introdução ao gerenciador de cópia

Para copiar um objeto de um bucket para outro ou modificar as propriedades de um objeto, use a operação de cópia simples ou a operação de cópia multipart. Cada operação é adequada para um cenário diferente:

  • A operação de cópia simples (CopyObject) é indicada apenas para copiar objetos menores que 5 GiB.

  • A operação de cópia multipart (UploadPartCopy) suporta a cópia de objetos maiores que 5 GiB. No entanto, essa operação não suporta os parâmetros (x-oss-metadata-directive) ou (x-oss-tagging-directive). Ao usá-la, especifique os metadados e as tags a serem copiados.

O gerenciador de cópia Copier é um novo recurso do OSS SDK for Python V2 que oferece uma interface de cópia universal. Essa interface abstrai os detalhes de implementação subjacentes e seleciona automaticamente a operação de cópia adequada com base nos parâmetros da requisição. O código a seguir apresenta os métodos comuns do Copier:

class CopyError(exceptions.BaseError):
  ...

def copier(self, **kwargs) -> Copier:
  ...

def copy(self, request: models.CopyObjectRequest, **kwargs: Any) -> CopyResult:
  ...

Parâmetros de requisição

Parâmetro

Tipo

Descrição

request

CopyObjectRequest

Os parâmetros de requisição da operação. Para mais informações, consulte CopyObjectRequest.

**kwargs

Any

(Opcional) Qualquer parâmetro do tipo dicionário.

A tabela a seguir descreve os parâmetros comuns de CopyObjectRequest.

Parâmetro

Tipo

Descrição

bucket

str

O nome do bucket de destino.

key

str

O nome do objeto de destino.

source_bucket

str

O nome do bucket de origem.

source_key

str

O nome do objeto de origem.

forbid_overwrite

str

Especifica se um objeto de destino com o mesmo nome deve ser sobrescrito durante a operação CopyObject.

tagging

str

As tags do objeto. É possível especificar várias tags ao mesmo tempo. Exemplo: TagA=A&TagB=B.

tagging_directive

str

Especifica como as tags do objeto de destino serão definidas. Valores válidos:

  • Copy (padrão): copia as tags do objeto de origem para o objeto de destino.

  • Replace: ignora as tags do objeto de origem e aplica ao objeto de destino as tags especificadas na requisição.

É possível personalizar o comportamento de cópia dos objetos especificando opções de configuração ao inicializar uma instância do gerenciador de cópia com client.copier. Também é possível definir opções de configuração em cada chamada de cópia para personalizar o comportamento de um objeto específico.

  • Defina os parâmetros de configuração do Copier

    copier = client.copier(
        part_size=100 * 1024 * 1024,
    )
  • Defina os parâmetros de configuração para cada requisição de cópia

    result = copier.copy(oss.CopyObjectRequest(
            bucket="example_bucket",
            key="example_key",
            source_bucket="example_source_bucket",
            source_key="example_source_key",
        ),
        part_size=100 * 1024 * 1024,
    )

A tabela a seguir descreve as opções de configuração comuns.

Parâmetro

Tipo

Descrição

part_size

int

O tamanho de cada parte. O valor padrão é 64 MiB.

parallel_num

int

O número de tarefas de cópia simultâneas. Valor padrão: 3. Este parâmetro define o limite de concorrência para uma única chamada, não o limite global.

multipart_copy_threshold

int64

O limiar para cópia multipart. O valor padrão é 200 MiB.

leave_parts_on_error

bool

Especifica se as partes já copiadas devem ser retidas em caso de falha. Por padrão, as partes copiadas não são retidas.

disable_shallow_copy

bool

Especifica se a cópia shallow deve ser desativada. Por padrão, a cópia shallow é utilizada.

Código de exemplo

O código de exemplo a seguir mostra como copiar um objeto de um bucket de origem para um bucket de destino.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="copier sample")

# Add the command-line parameter: region (required), which specifies the region where the bucket is located.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the command-line parameter: bucket (required), which specifies the name of the destination bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the command-line parameter: endpoint (optional), which specifies the endpoint for accessing OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# Add the command-line parameter: key (required), which specifies the name of the destination object.
parser.add_argument('--key', help='The name of the object.', required=True)

# Add the command-line parameter: source_key (required), which specifies the name of the source object.
parser.add_argument('--source_key', help='The name of the source address for object.', required=True)

# Add the command-line parameter: source_bucket (required), which specifies the name of the source bucket.
parser.add_argument('--source_bucket', help='The name of the source address for bucket.', required=True)

def main():
    # Parse the command-line arguments.
    args = parser.parse_args()

    # Load credentials from environment variables.
    # Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider  # Set the credential provider.
    cfg.region = args.region  # Set the region where the bucket is located.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint  # If an endpoint is provided, set a custom endpoint.

    # Create an OSS client instance.
    client = oss.Client(cfg)

    # Create a Copier instance and perform the object copy operation.
    copier = client.copier()

    # Perform the object copy operation.
    result = copier.copy(
        oss.CopyObjectRequest(
            bucket=args.bucket,          # The name of the destination bucket.
            key=args.key,                # The name of the destination object.
            source_bucket=args.source_bucket,  # The name of the source bucket.
            source_key=args.source_key   # The name of the source object.
        )
    )

    # Print the copy result.
    # Use vars(result) to convert the result object to the dictionary format and print the result.
    print(vars(result))

if __name__ == "__main__":
    main()

Cenários

Usar o gerenciador de cópia para definir o tamanho de parte e a concorrência

O código de exemplo a seguir mostra como configurar os parâmetros do gerenciador de cópia para definir o tamanho de parte e a concorrência.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="copier sample")

# Add the command-line parameter: region (required), which specifies the region where the bucket is located.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the command-line parameter: bucket (required), which specifies the name of the destination bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the command-line parameter: endpoint (optional), which specifies the endpoint for accessing OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# Add the command-line parameter: key (required), which specifies the name of the destination object.
parser.add_argument('--key', help='The name of the object.', required=True)

# Add the command-line parameter: source_key (required), which specifies the name of the source object.
parser.add_argument('--source_key', help='The name of the source address for object.', required=True)

# Add the command-line parameter: source_bucket (required), which specifies the name of the source bucket.
parser.add_argument('--source_bucket', help='The name of the source address for bucket.', required=True)

def main():
    # Parse the command-line arguments.
    args = parser.parse_args()

    # Load credentials from environment variables.
    # Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider  # Set the credential provider.
    cfg.region = args.region  # Set the region where the bucket is located.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint  # If an endpoint is provided, set a custom endpoint.

    # Create an OSS client instance.
    client = oss.Client(cfg)

    # Create a Copier instance and perform the object copy operation.
    copier = client.copier()

    # Perform the object copy operation.
    result = copier.copy(
        oss.CopyObjectRequest(
            bucket=args.bucket,          # The name of the destination bucket.
            key=args.key,                # The name of the destination object.
            source_bucket=args.source_bucket,  # The name of the source bucket.
            source_key=args.source_key   # The name of the source object.
        ),
        part_size= 1 * 1024 * 1024,          # The part size in bytes. In this example, the part size is set to 1 MiB.
        parallel_num=5,                 # The number of concurrent tasks. This parameter specifies the number of parts that can be copied at the same time.
        leave_parts_on_error=True,      # If the copy fails, retain the copied parts.
    )

    # Print the copy result.
    # Use vars(result) to convert the result object to the dictionary format and print the result.
    print(vars(result))

if __name__ == "__main__":
    main()

Usar o gerenciador de cópia para exibir uma barra de progresso

O código de exemplo a seguir mostra como usar uma barra de progresso para acompanhar o andamento da cópia.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="copier sample")

# Add the command-line parameter: region (required), which specifies the region where the bucket is located.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the command-line parameter: bucket (required), which specifies the name of the destination bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the command-line parameter: endpoint (optional), which specifies the endpoint for accessing OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# Add the command-line parameter: key (required), which specifies the name of the destination object.
parser.add_argument('--key', help='The name of the object.', required=True)

# Add the command-line parameter: source_key (required), which specifies the name of the source object.
parser.add_argument('--source_key', help='The name of the source address for object.', required=True)

# Add the command-line parameter: source_bucket (required), which specifies the name of the source bucket.
parser.add_argument('--source_bucket', help='The name of the source address for bucket.', required=True)

def main():
    # Parse the command-line arguments.
    args = parser.parse_args()

    # Load credentials from environment variables.
    # Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider  # Set the credential provider.
    cfg.region = args.region  # Set the region where the bucket is located.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint  # If an endpoint is provided, set a custom endpoint.

    # Create an OSS client instance.
    client = oss.Client(cfg)

    # Define a dictionary variable named progress_state to save the copy progress. The initial value is 0.
    progress_state = {'saved': 0}
    def _progress_fn(n, written, total):
        # Use the dictionary to store the accumulated number of written bytes to avoid using global variables.
        progress_state['saved'] += n

        # Calculate the current copy percentage. The value is obtained by dividing the number of written bytes by the total number of bytes and rounding down the result.
        rate = int(100 * (float(written) / float(total)))

        # Print the current copy progress. \r indicates returning to the beginning of the line to implement real-time refresh in the command line.
        # end='' indicates no line break, which allows the next print to overwrite the current line.
        print(f'\rCopy progress: {rate}% ', end='')

    # Create a Copier instance and perform the object copy operation.
    copier = client.copier()

    # Perform the object copy operation.
    result = copier.copy(
        oss.CopyObjectRequest(
            bucket=args.bucket,          # The name of the destination bucket.
            key=args.key,                # The name of the destination object.
            source_bucket=args.source_bucket,  # The name of the source bucket.
            source_key=args.source_key,   # The name of the source object.
            progress_fn=_progress_fn,   # Set the progress callback function.
        )
    )

    # Print the copy result.
    # Use vars(result) to convert the result object to the dictionary format and print the result.
    print(vars(result))

if __name__ == "__main__":
    main()

Referências

  • Para mais informações sobre o gerenciador de cópia, consulte Developer Guide.

  • Para o código de exemplo completo do gerenciador de cópia, consulte copier.py.