Todos os produtos
Search
Central de documentação

Object Storage Service:Processamento assíncrono com o OSS SDK for Python 2.0

Última atualização: Sep 22, 2026

O processamento assíncrono (x-oss-async-process) permite que um programa continue executando outras tarefas sem aguardar a conclusão de uma tarefa. Use o OSS SDK for Python V2 para processar dados de forma assíncrona, como conversão de documentos, transcodificação de vídeo e mesclagem de vídeos.

Notas de uso

  • O código de exemplo usa o ID da região cn-hangzhou (China (Hangzhou)) com um endpoint público. 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 as regiões e endpoints do OSS, consulte Regions and endpoints.

Definição do método

async_process_object(request: AsyncProcessObjectRequest, **kwargs) → AsyncProcessObjectResult

Parâmetros de requisição

Parâmetro

Tipo

Descrição

request

AsyncProcessObjectRequest

Os parâmetros de requisição da operação AsyncProcessObject. AsyncProcessObjectRequest.

Parâmetros de resposta

Tipo

Descrição

AsyncProcessObjectResult

O objeto de resposta. AsyncProcessObjectResult.

Definição completa do método: async_process_object.

Código de exemplo

O exemplo a seguir converte o formato de um documento:

import base64
import argparse
import alibabacloud_oss_v2 as oss

# Create a parser for parsing command-line arguments and describe the purpose of the script.
parser = argparse.ArgumentParser(description="async process object sample")

# Specify command-line arguments, including the required region, source bucket name, endpoint, and source object name, destination object name, and destination bucket name.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--target_key', help='Specify the name of the processed object.', required=True)
parser.add_argument('--target_bucket', help='Specify the name of the bucket used to store processed object.', required=True)

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

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration to create a cfg object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region attribute of the cfg object to the region provided in the command line.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding settings to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Define a style for converting DOCX to PNG.
    style = "doc/convert,target_png,source_docx"

    # Base64-encode the destination bucket name and object name to make them URL-safe.
    target_bucket_base64 = base64.b64encode(args.target_bucket.encode()).decode()
    target_key_base64 = base64.b64encode(args.target_key.encode()).decode()

    # Create a process instruction that includes the style and destination path.
    process = f"{style}|sys/saveas,o_{target_key_base64},b_{target_bucket_base64}"

    # Send the request to asynchronously process the object and store the resulting object in the destination bucket.
    result = client.async_process_object(oss.AsyncProcessObjectRequest(
        bucket=args.bucket,  # The source bucket name.
        key=args.key,  # The source object name.
        process=process, # The processing instruction.
    ))

    # Display the status code and other result information to check the request status and result.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' event id: {result.event_id},'
          f' task id: {result.task_id},'
          f' process request id: {result.process_request_id},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main()  # Specify the entry point of the script. The control flow starts here.

Cenários comuns

Transcodificação de vídeo

A transcodificação de vídeo altera os formatos de codificação e contêiner de um vídeo e reduz o tamanho do arquivo ao ajustar a resolução e a taxa de bits. O exemplo a seguir transcodifica um vídeo:

import base64
import argparse
import alibabacloud_oss_v2 as oss

# Create the parser for parsing command-line arguments and describe the purpose of the script.
parser = argparse.ArgumentParser(description="async process object sample")

# Specify command-line arguments, including the required region, source bucket name, endpoint, and source object name, destination object name, and destination bucket name.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--target_key', help='Specify the name of the processed object.', required=True)
parser.add_argument('--target_bucket', help='Specify the name of the bucket used to store processed object.', required=True)

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

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration to create a cfg object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region attribute of the cfg object to the region provided in the command line.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding settings to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Define a style for video processing. In this example, the video transcoding settings include the container format, encoding format, resolution, video bit rate, frame rate, audio codec, and audio bit rate.
    style = "video/convert,f_avi,vcodec_h265,s_1920x1080,vb_2000000,fps_30,acodec_aac,ab_100000,sn_1"

    # Base64-encode the destination bucket name and object name to make them URL-safe.
    target_bucket_base64 = base64.b64encode(args.target_bucket.encode()).decode()
    target_key_base64 = base64.b64encode(args.target_key.encode()).decode()

    # Create a process instruction that includes the style and destination path.
    process = f"{style}|sys/saveas,o_{target_key_base64},b_{target_bucket_base64}"

    # Send the request to asynchronously process the object and store the resulting object in the destination bucket.
    result = client.async_process_object(oss.AsyncProcessObjectRequest(
        bucket=args.bucket,  # The source bucket name.
        key=args.key,  # The source object name.
        process=process, # The processing instruction.
    ))

    # Display the status code and other result information to check the request status and result.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' event id: {result.event_id},'
          f' task id: {result.task_id},'
          f' process request id: {result.process_request_id},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main()  # Specify the entry point of the script. The control flow starts here.

Conversão de vídeo em imagem animada

A conversão de vídeo em imagem animada extrai quadros de um vídeo e produz animações em GIF ou WebP. O exemplo a seguir cria uma imagem animada a partir de um vídeo:

import base64
import argparse
import alibabacloud_oss_v2 as oss

# Create the parser for parsing command-line arguments and describe the purpose of the script.
parser = argparse.ArgumentParser(description="async process object sample")

# Specify command-line arguments, including the required region, source bucket name, endpoint, and source object name, destination object name, and destination bucket name.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--target_key', help='Specify the name of the processed object.', required=True)
parser.add_argument('--target_bucket', help='Specify the name of the bucket used to store processed object.', required=True)

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

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration to create a cfg object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region attribute of the cfg object to the region provided in the command line.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding settings to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Define a style for converting the video to an animated image. In this example, the settings include the GIF width, the GIF height, and the time interval for capturing frames.
    style = "video/animation,f_gif,w_100,h_100,inter_1000"

    # Base64-encode the destination bucket name and object name to make them URL-safe.
    target_bucket_base64 = base64.b64encode(args.target_bucket.encode()).decode()
    target_key_base64 = base64.b64encode(args.target_key.encode()).decode()

    # Create a process instruction that includes the style and destination path.
    process = f"{style}|sys/saveas,o_{target_key_base64},b_{target_bucket_base64}"

    # Send the request to asynchronously process the object and store the resulting object in the destination bucket.
    result = client.async_process_object(oss.AsyncProcessObjectRequest(
        bucket=args.bucket,  # The source bucket name.
        key=args.key,  # The source object name.
        process=process, # The processing instruction.
    ))

    # Display the status code and other result information to check the request status and result.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' event id: {result.event_id},'
          f' task id: {result.task_id},'
          f' process request id: {result.process_request_id},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main()  # Specify the entry point of the script. The control flow starts here.

Captura de quadros

A captura de quadros extrai quadros de vídeo e os converte em um formato de imagem especificado. O exemplo a seguir captura quadros de um vídeo:

import base64
import argparse
import alibabacloud_oss_v2 as oss

# Create the parser for parsing command-line arguments and describe the purpose of the script.
parser = argparse.ArgumentParser(description="async process object sample")

# Specify command-line arguments, including the required region, source bucket name, endpoint, and source object name, destination object name, and destination bucket name.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--target_key', help='Specify the name of the processed object.', required=True)
parser.add_argument('--target_bucket', help='Specify the name of the bucket used to store processed object.', required=True)

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

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration to create a cfg object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region attribute of the cfg object to the region provided in the command line.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding settings to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Define a style for frame capture.
    style = "video/snapshots,f_jpg,w_100,h_100,scaletype_crop,inter_10000"

    # Base64-encode the destination bucket name and object name to make them URL-safe.
    target_bucket_base64 = base64.b64encode(args.target_bucket.encode()).decode()
    target_key_base64 = base64.b64encode(args.target_key.encode()).decode()

    # Create a process instruction that includes the style and destination path.
    process = f"{style}|sys/saveas,o_{target_key_base64},b_{target_bucket_base64}"

    # Send the request to asynchronously process the object and store the resulting object in the destination bucket.
    result = client.async_process_object(oss.AsyncProcessObjectRequest(
        bucket=args.bucket,  # The source bucket name.
        key=args.key,  # The source object name.
        process=process, # The processing instruction.
    ))

    # Display the status code and other result information to check the request status and result.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' event id: {result.event_id},'
          f' task id: {result.task_id},'
          f' process request id: {result.process_request_id},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main()  # Specify the entry point of the script. The control flow starts here.

Transcodificação de áudio

A transcodificação de áudio converte arquivos de áudio entre formatos. O exemplo a seguir transcodifica um arquivo de áudio:

import base64
import argparse
import alibabacloud_oss_v2 as oss

# Create the parser for parsing command-line arguments and describe the purpose of the script.
parser = argparse.ArgumentParser(description="async process object sample")

# Specify command-line arguments, including the required region, source bucket name, endpoint, and source object name, destination object name, and destination bucket name.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--target_key', help='Specify the name of the processed object.', required=True)
parser.add_argument('--target_bucket', help='Specify the name of the bucket used to store processed object.', required=True)

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

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration to create a cfg object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region attribute of the cfg object to the region provided in the command line.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding settings to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Define a style for audio transcoding.
    style = "audio/convert,ss_10000,t_60000,f_aac,ab_96000"

    # Base64-encode the destination bucket name and object name to make them URL-safe.
    target_bucket_base64 = base64.b64encode(args.target_bucket.encode()).decode()
    target_key_base64 = base64.b64encode(args.target_key.encode()).decode()

    # Create a process instruction that includes the style and destination path.
    process = f"{style}|sys/saveas,o_{target_key_base64},b_{target_bucket_base64}"

    # Send the request to asynchronously process the object and store the resulting object in the destination bucket.
    result = client.async_process_object(oss.AsyncProcessObjectRequest(
        bucket=args.bucket,  # The source bucket name.
        key=args.key,  # The source object name.
        process=process, # The processing instruction.
    ))

    # Display the status code and other result information to check the request status and result.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' event id: {result.event_id},'
          f' task id: {result.task_id},'
          f' process request id: {result.process_request_id},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main()  # Specify the entry point of the script. The control flow starts here.

Decodificação de marca d'água invisível

O exemplo a seguir decodifica uma marca d'água invisível de uma imagem:

import base64
import argparse
import alibabacloud_oss_v2 as oss

# Create a parser for parsing command-line arguments and describe the purpose of the script.
parser = argparse.ArgumentParser(description="async process object sample")

# Specify command-line arguments, including the required region, source bucket name, endpoint, and source object name, destination object name, and destination bucket name.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--target_key', help='Specify the name of the processed object.', required=True)
parser.add_argument('--target_bucket', help='Specify the name of the bucket used to store processed object.', required=True)

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

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration to create a cfg object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region attribute of the cfg object to the region provided in the command line.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding settings to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Decode the watermark from the specified image.
    style = "image/deblindwatermark,s_low,t_text"

    # Base64-encode the destination bucket name and object name to make them URL-safe.
    target_bucket_base64 = base64.b64encode(args.target_bucket.encode()).decode()
    target_key_base64 = base64.b64encode(args.target_key.encode()).decode()

    # Create a process instruction that includes the style and destination path.
    process = f"{style}|sys/saveas,o_{target_key_base64},b_{target_bucket_base64}"

    # Send the request to asynchronously process the object and store the resulting object in the destination bucket.
    result = client.async_process_object(oss.AsyncProcessObjectRequest(
        bucket=args.bucket,  # The source bucket name.
        key=args.key,  # The source object name.
        process=process, # The processing instruction.
    ))

    # Display the status code and other result information to check the request status and result.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' event id: {result.event_id},'
          f' task id: {result.task_id},'
          f' process request id: {result.process_request_id},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main()  # Specify the entry point of the script. The control flow starts here.

Referências