Devido à política de mesma origem, os navegadores podem rejeitar solicitações de origem cruzada durante a troca de dados ou o compartilhamento de recursos entre nomes de domínio diferentes. Para resolver esse problema, configure as regras de compartilhamento de recursos de origem cruzada (CORS). Nessas regras, especifique os nomes de domínio de origem das solicitações, os métodos de envio de solicitações de origem cruzada e os cabeçalhos permitidos.
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região do OSS, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.
Neste tópico, o código obtém as credenciais de acesso a partir de variáveis de ambiente. Para saber mais sobre como configurar credenciais de acesso, consulte Configure access credentials using OSS SDK for Python 1.0.
Este tópico demonstra como criar uma instância do OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Initialization.
Configurar regras de CORS requer a permissão
oss:PutBucketCors. Para consultar essas regras, você precisa da permissãooss:GetBucketCors. Já para excluí-las, é obrigatório ter a permissãooss:DeleteBucketCors. Para obter mais informações, consulte Grant a custom policy.
Configure regras de CORS
O código de exemplo a seguir mostra como configurar uma regra de CORS para um bucket específico:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import BucketCors, CorsRule
# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
rule = CorsRule(allowed_origins=['*'],
allowed_methods=['GET', 'HEAD'],
allowed_headers=['*'],
max_age_seconds=1000)
# An existing rule with the same name is overwritten.
bucket.put_bucket_cors(BucketCors([rule]))
Consulte regras de CORS
O código de exemplo a seguir mostra como consultar as regras de CORS de um bucket específico:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
try:
cors = bucket.get_bucket_cors()
except oss2.exceptions.NoSuchCors:
print('cors is not set')
else:
for rule in cors.rules:
print('AllowedOrigins={0}'.format(rule.allowed_origins))
print('AllowedMethods={0}'.format(rule.allowed_methods))
print('AllowedHeaders={0}'.format(rule.allowed_headers))
print('ExposeHeaders={0}'.format(rule.expose_headers))
print('MaxAgeSeconds={0}'.format(rule.max_age_seconds))
Exclua regras de CORS
O código de exemplo a seguir mostra como excluir todas as regras de CORS de um bucket específico:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
bucket.delete_bucket_cors()
Referências
Para acessar o código de exemplo completo para gerenciar regras de CORS, visite o GitHub.
Para obter mais informações sobre a operação de API que você pode usar para configurar regras de CORS, consulte PutBucketCors.
Para saber mais sobre a operação de API que você pode usar para consultar regras de CORS, consulte GetBucketCors.
Para mais detalhes sobre a operação de API que você pode usar para excluir regras de CORS, consulte DeleteBucketCors.