Todos os produtos
Search
Central de documentação

Object Storage Service:Configure tags de bucket usando o OSS SDK for Python 1.0

Última atualização: Sep 25, 2026

As tags de bucket permitem que você classifique e gerencie buckets do Object Storage Service (OSS) com eficiência. Por exemplo, ao chamar a operação ListBuckets, você pode listar apenas os buckets que possuem tags específicas.

Notas de uso

  • Neste tópico, é utilizado 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, use um endpoint interno. Para mais informações sobre as regiões e endpoints do OSS, consulte Regions and endpoints.

  • As credenciais de acesso são obtidas de variáveis de ambiente. Para configurar as credenciais de acesso, consulte Configure access credentials using OSS SDK for Python 1.0.

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

  • Apenas o proprietário do bucket e usuários com a permissão oss:PutBucketTagging podem configurar tags para buckets. Se outros usuários tentarem configurar tags, o sistema retornará a mensagem 403 Forbidden contendo o código de erro AccessDenied.

  • É possível configurar até 20 tags para um único bucket.

  • A chave e o valor de uma tag devem ser codificados em UTF-8.

  • A chave pode ter até 64 caracteres e diferencia maiúsculas de minúsculas. Ela não pode estar vazia nem começar com http://, https:// ou Aliyun. Esses prefixos não diferenciam maiúsculas de minúsculas.

  • O valor de uma tag pode ter até 128 caracteres e pode estar vazio.

Configure tags para um bucket

O código de exemplo a seguir mostra como configurar tags para um bucket chamado examplebucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import Tagging, TaggingRule

# 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)

# Create tagging rules for the bucket. 
rule = TaggingRule()
rule.add('key1', 'value1')
rule.add('key2', 'value2')

# Create tags for the bucket. 
tagging = Tagging(rule)
# Configure tags for the bucket. 
result = bucket.put_bucket_tagging(tagging)
# Display the returned HTTP status code. 
print('http status:', result.status)

Consultar as tags de um bucket

O código de exemplo a seguir mostra como consultar as tags de um bucket chamado examplebucket:

# -*- 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)

# Query the tags of the bucket. 
result = bucket.get_bucket_tagging()
# Display the tagging rule. 
tag_rule = result.tag_set.tagging_rule
print('tag rule:', tag_rule)

Liste buckets com tags específicas

O código de exemplo a seguir mostra como listar buckets que possuem tags específicas:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Create a server object. 
# 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"

service = oss2.Service(auth, endpoint, region=region)

# Add the tag-key and tag-value fields to the params parameter of the ListBuckets operation. 
params = {}
params['tag-key'] = 'yourTagging_key'
params['tag-value'] = 'yourTagging_value'

# List buckets that have specific tags. 
result = service.list_buckets(params=params)
# Display the results of the list operation. 
for bucket in result.buckets:
    print('result bucket_name:', bucket.name)

Exclua as tags de um bucket

Exclua todas as tags de um bucket

O código de exemplo a seguir mostra como excluir todas as tags de um bucket chamado examplebucket:

# -*- 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)

# Delete tags of the bucket. 
result = bucket.delete_bucket_tagging()
# Display the returned HTTP status code. 
print('http status:', result.status)

Exclua uma tag específica de um bucket

O código de exemplo a seguir mostra como excluir uma tag específica de um bucket chamado examplebucket:

# -*- 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.ProviderAuth(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. 
# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

params = dict()
# Delete the tag whose key is key1. 
params['tagging'] = "key1"
# Delete the specified tag of the bucket. 
result = bucket.delete_bucket_tagging(params=params)
# Display the returned HTTP status code. 
print('http status:', result.status)

Referências

  • Para acessar o código de exemplo completo sobre o gerenciamento de tags de um bucket, acesse o GitHub.

  • Para mais informações sobre a operação de API para definir tags de bucket, consulte PutBucketTags.

  • Se precisar de detalhes sobre a operação de API para obter tags de bucket, consulte GetBucketTags.

  • Consulte DeleteBucketTags para entender a operação de API voltada a excluir tags de bucket.