Todos os produtos
Search
Central de documentação

Object Storage Service:Bucket policy (Python SDK V1)

Última atualização: Sep 22, 2026

Políticas de bucket controlam o acesso de usuários anônimos, contas Alibaba Cloud, usuários RAM e funções RAM a recursos do Object Storage Service (OSS). Por exemplo, é possível conceder permissões de somente leitura em recursos específicos do OSS para um usuário RAM de outra conta Alibaba Cloud.

Observações

  • Antes de configurar uma política de bucket, certifique-se de compreender este recurso. Para mais informações, consulte Bucket Policy.

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outro serviço da Alibaba Cloud na mesma região, utilize um endpoint interno. Para mais informações sobre as regiões e os endpoints do OSS, consulte Regions and endpoints.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais informações 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 OSSClient usando 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.

  • Para definir uma política de bucket, é necessária a permissão oss:PutBucketPolicy. Para obter uma política de bucket, você deve ter a permissão oss:GetBucketPolicy. Para excluir uma política de bucket, é preciso ter a permissão oss:DeleteBucketPolicy. Para mais informações, consulte Grant a custom policy.

Definir uma política de bucket

O código de exemplo a seguir demonstra como definir uma política de bucket:

# -*- coding: utf-8 -*-

import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import json

# Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Set the Endpoint to the URL of the region where your bucket is located. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Set the region that corresponds to your Endpoint, such as cn-hangzhou. This parameter is required for v4 signatures.
region = "cn-hangzhou"

# Set yourBucketName to the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# In this example, the resource owner (bucket owner with UID 174649585760xxxx) uses a bucket policy to grant a Resource Access Management (RAM) user (UID 20214760404935xxxx) permission to list all files in the examplebucket.
policy_text = '{"Statement": [{"Effect": "Allow", "Action": ["oss:GetObject", "oss:ListObjects"], "Principal": ["20214760404935xxxx"], "Resource": ["acs:oss:*:174649585760xxxx:examplebucket/*"]}], "Version": "1"}'

# Upload the authorization policy.
bucket.put_bucket_policy(policy_text)

Obter uma política de bucket

O código de exemplo a seguir demonstra como obter uma política de bucket:

# -*- coding: utf-8 -*-

import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import json
# Get access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the Endpoint for your bucket's region. For example, if your bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the region that corresponds to the Endpoint, such as cn-hangzhou. Note: This parameter is required for V4 signatures.
region = "cn-hangzhou"

# Set yourBucketName to the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Get the bucket policy.
result = bucket.get_bucket_policy()
policy_json = json.loads(result.policy) 
print("Get policy text: ", policy_json)

Excluir uma política de bucket

O código de exemplo a seguir demonstra como excluir uma política de bucket:

# -*- coding: utf-8 -*-

import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Get access credentials from environment variables. Before running this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Set the Endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Set the region that corresponds to the Endpoint, such as cn-hangzhou. Note: This parameter is required for V4 signatures.
region = "cn-hangzhou"

# Set yourBucketName to the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Delete the bucket policy.
result = bucket.delete_bucket_policy()
assert int(result.status)//100 == 2

Referências

  • Para um exemplo de código completo de uma política de bucket, consulte o exemplo no GitHub.

  • Para a referência da API para definir uma política de bucket, consulte PutBucketPolicy.

  • Para a referência da API para obter uma política de bucket, consulte GetBucketPolicy.

  • Para a referência da API para excluir uma política de bucket, consulte DeleteBucketPolicy.