Todos os produtos
Search
Central de documentação

Object Storage Service:Bucket policy (Python SDK V1)

Última atualização: Jul 03, 2026

Uma política de bucket permite autorizar ou restringir o acesso de usuários anônimos ou outros usuários, como contas Alibaba Cloud, usuários RAM e funções RAM, a recursos específicos do Object Storage Service (OSS). Por exemplo, você pode conceder permissões somente leitura em recursos específicos do OSS a um usuário RAM de outra conta Alibaba Cloud.

Observações

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

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

  • As credenciais de acesso neste tópico são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização.

  • Para definir uma política de bucket, é necessária a permissão oss:PutBucketPolicy. Para obter uma política de bucket, é necessária a permissão oss:GetBucketPolicy. Para excluir uma política de bucket, é necessária a permissão oss:DeleteBucketPolicy. Para mais informações, consulte Conceder uma política personalizada.

Definir uma política de bucket

O código abaixo exemplifica 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 exemplo a seguir mostra o código para 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

Confira abaixo o código de exemplo para 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 completo de código de política de bucket, consulte o exemplo no GitHub.

  • Para consultar a referência da API sobre como definir uma política de bucket, veja PutBucketPolicy.

  • A documentação da API para obter uma política de bucket está disponível em GetBucketPolicy.

  • Para excluir uma política de bucket via API, consulte DeleteBucketPolicy.