Todos os produtos
Search
Central de documentação

Object Storage Service:Compartilhamento de recursos de origem cruzada (Python SDK V2)

Última atualização: Jul 03, 2026

Os navegadores aplicam a política de mesma origem e podem rejeitar solicitações entre domínios diferentes. Configure regras de compartilhamento de recursos de origem cruzada (CORS) para especificar origens permitidas, métodos de solicitação e cabeçalhos.

Observações

  • O código de exemplo deste tópico usa o ID da região cn-hangzhou referente à região China (Hangzhou). Por padrão, o acesso aos recursos de um bucket utiliza um endpoint público. Para acessar recursos no bucket a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre as regiões e endpoints compatíveis com o OSS, consulte Regiões e endpoints do OSS.

  • A configuração de regras CORS exige a permissão oss:PutBucketCors. A consulta requer a permissão oss:GetBucketCors, enquanto a exclusão demanda a permissão oss:DeleteBucketCors. Para mais detalhes, consulte Conceder política personalizada a usuários RAM.

Definição de métodos

Configurar regras CORS

put_bucket_cors(request: PutBucketCorsRequest, **kwargs) → PutBucketCorsResult

Consultar regras CORS

get_bucket_cors(request: GetBucketCorsRequest, **kwargs) → GetBucketCorsResult

Excluir regras CORS

delete_bucket_cors(request: DeleteBucketCorsRequest, **kwargs) → DeleteBucketCorsResult

Parâmetros de solicitação

Parâmetro

Tipo

Descrição

request

PutBucketCorsRequest

Parâmetro da solicitação. Para mais informações, consulte PutBucketCorsRequest

GetBucketCorsRequest

Parâmetro da solicitação. Para mais informações, consulte GetBucketCorsRequest

DeleteBucketCorsRequest

Parâmetro da solicitação. Para mais informações, consulte DeleteBucketCorsRequest

Parâmetros de resposta

Tipo

Descrição

PutBucketCorsResult

Valor de retorno. Para mais informações, consulte PutBucketCorsResult

GetBucketCorsResult

Valor de retorno. Para mais informações, consulte GetBucketCorsResult

DeleteBucketCorsResult

Valor de retorno. Para mais informações, consulte DeleteBucketCorsResult

Para obter mais detalhes sobre a configuração de regras CORS, consulte put_bucket_cors.

Para saber mais sobre a consulta de regras CORS, veja get_bucket_cors.

Quanto à exclusão de regras CORS, consulte delete_bucket_cors.

Código de exemplo

Configure CORS rules

O código abaixo configura regras CORS para um bucket específico.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: Configure CORS for a bucket.
parser = argparse.ArgumentParser(description="put bucket cors sample")

# Define command-line arguments, including the required region and bucket name, and the optional endpoint and response_vary.
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('--response_vary', help='Indicates whether the Vary: Origin header was returned. Default value: false', default='false')

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

    # Load access credential information 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

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    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 to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to configure CORS for the specified bucket.
    result = client.put_bucket_cors(oss.PutBucketCorsRequest(
            bucket=args.bucket,  # The bucket name.
            cors_configuration=oss.CORSConfiguration(
                cors_rules=[
                    # The first CORS rule.
                    oss.CORSRule(
                        allowed_origins=['*'],  # Allow all origins.
                        allowed_methods=['GET', 'HEAD'],  # The allowed methods.
                        allowed_headers=['GET'],  # The allowed request headers.
                        expose_headers=['x-oss-test', 'x-oss-test1'],  # The exposed response headers.
                        max_age_seconds=33012,  # The validity period of the preflight request.
                    ),
                    # The second CORS rule.
                    oss.CORSRule(
                        allowed_origins=['http://www.example.com'],  # Allow specific origins.
                        allowed_methods=['PUT', 'POST'],  # The allowed methods.
                        allowed_headers=['*'],  # Allow all request headers.
                        expose_headers=['x-oss-test2', 'x-oss-test3'],  # The exposed response headers.
                        max_age_seconds=33012,  # The validity period of the preflight request.
                    )
                ],
                response_vary=args.response_vary,  # Specifies whether to return the Vary: Origin header. The default value is False.
            ),
    ))

    # Print the status code and request ID of the operation result to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          )

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

Query CORS rules

O exemplo a seguir consulta as regras CORS configuradas para um bucket.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: Query the CORS configuration of a bucket.
parser = argparse.ArgumentParser(description="get bucket cors sample")

# Define command-line arguments, including the required region and bucket name, and the optional endpoint.
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')

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

    # Load access credential information 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

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    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 to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to query the CORS configuration of the specified bucket.
    result = client.get_bucket_cors(oss.GetBucketCorsRequest(
            bucket=args.bucket,  # The bucket name.
    ))

    # Print the status code, request ID, and response vary value of the operation result.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' response vary: {result.cors_configuration.response_vary},'
          )

    # Traverse and print the details of each CORS rule.
    for r in result.cors_configuration.cors_rules:
        print(f'result: {r.max_age_seconds}, {r.allowed_origins}, {r.allowed_methods}, {r.allowed_headers}, {r.expose_headers}')

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

Delete CORS rules

Este código exclui todas as regras CORS de um bucket específico.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: Delete the CORS configuration of a bucket.
parser = argparse.ArgumentParser(description="delete bucket cors sample")

# Define command-line arguments, including the required region and bucket name, and the optional endpoint.
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')

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

    # Load access credential information 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

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    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 to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to delete the CORS configuration of the specified bucket.
    result = client.delete_bucket_cors(oss.DeleteBucketCorsRequest(
            bucket=args.bucket,  # The bucket name.
    ))

    # Print the status code and request ID of the operation result to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          )

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

Referências

  • Para solucionar erros comuns de configuração CORS, consulte 34-CORS.

  • Acesse o código de exemplo completo para configurar regras CORS em put_bucket_cors.py.

  • O código de exemplo completo para consultar regras CORS está disponível em get_bucket_cors.py.

  • Veja o código de exemplo completo para excluir regras CORS em delete_bucket_cors.py.