No processamento síncrono, o programa precisa concluir a tarefa atual antes de iniciar qualquer tarefa adicional. Para processar dados de forma síncrona no Object Storage Service (OSS), utilize o parâmetro x-oss-process. Este tópico descreve como usar o OSS SDK for Python V2 em cenários de processamento síncrono, como processamento de imagens e de documentos.
Observações de uso
O código de exemplo neste tópico usa o ID de região
cn-hangzhouda região China (Hangzhou). Por padrão, o endpoint público é usado para acessar recursos em um bucket. Para acessar recursos no bucket a partir de outros serviços da Alibaba Cloud na mesma região em que o bucket está localizado, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.
Definição do método
process_object(request: ProcessObjectRequest, **kwargs) → ProcessObjectResult
Parâmetros da requisição
|
Parâmetro |
Tipo |
Descrição |
|
request |
ProcessObjectRequest |
O parâmetro da requisição. Para mais informações, consulte ProcessObjectRequest. |
Parâmetros de resposta
|
Tipo |
Descrição |
|
ProcessObjectResult |
O valor de retorno. Para mais informações, consulte ProcessObjectResult. |
Para a definição completa do método, consulte process_object.
Código de exemplo
O código de exemplo a seguir redimensiona uma imagem e armazena a imagem redimensionada no bucket especificado usando o OSS SDK for Python V2:
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="process object sample")
# Specify command-line arguments, including the required region, source bucket name, endpoint, and source object name, style, 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('--style', help='The style to apply for processing the object, such as image resizing.', required=True)
parser.add_argument('--target_image', help='Specify the name of the processed image.', required=True)
parser.add_argument('--target_bucket', help='Specify the name of the bucket used to store processed images.', 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)
# Get the style for processing objects.
# The following sample style resizes an image: style = 'image/resize,m_fixed,w_100,h_100'
style = args.style
# 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_image.encode()).decode()
# Create a process instruction that includes the style and destination bucket name.
process = f"{style}|sys/saveas,o_{target_key_base64},b_{target_bucket_base64}"
# Send the request to process the object and store the resulting object in the destination bucket.
result = client.process_object(oss.ProcessObjectRequest(
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' bucket: {result.bucket},'
f' file size: {result.file_size},'
f' key: {result.key},'
f' process status: {result.process_status},'
)
# 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.