Todos los productos
Search
Centro de documentos

Object Storage Service:Configuración de etiquetas de bucket con OSS SDK for Python 1.0

Última actualización: Sep 25, 2026

Las etiquetas de bucket le permiten clasificar y gestionar de forma eficiente los buckets de Object Storage Service (OSS). Por ejemplo, al llamar a la operación ListBuckets, puede listar únicamente los buckets que tengan etiquetas específicas.

Notas de uso

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen a partir de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.

  • Solo el propietario del bucket y los usuarios con el permiso oss:PutBucketTagging pueden configurar etiquetas para los buckets. Si otros usuarios intentan configurar etiquetas, el sistema devuelve el mensaje 403 Forbidden con el código de error AccessDenied.

  • Se pueden configurar hasta 20 etiquetas por bucket.

  • La clave y el valor de una etiqueta deben codificarse en UTF-8.

  • La clave admite hasta 64 caracteres y distingue entre mayúsculas y minúsculas. No puede dejarse vacía ni comenzar con http://, https:// o Aliyun. Estos prefijos no distinguen entre mayúsculas y minúsculas.

  • El valor de una etiqueta admite hasta 128 caracteres y puede dejarse vacío.

Configurar etiquetas para un bucket

A continuación se muestra un ejemplo de código para configurar etiquetas en un bucket llamado 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 las etiquetas de un bucket

A continuación se muestra un ejemplo de código para consultar las etiquetas de un bucket llamado 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)

Listar buckets con etiquetas específicas

A continuación se muestra un ejemplo de código para listar los buckets que tienen etiquetas 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)

Eliminar las etiquetas de un bucket

Eliminar todas las etiquetas de un bucket

A continuación se muestra un ejemplo de código para eliminar todas las etiquetas de un bucket llamado 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)

Eliminar una etiqueta específica de un bucket

A continuación se muestra un ejemplo de código para eliminar una etiqueta específica de un bucket llamado 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)

Referencias

  • Para consultar el código de ejemplo completo sobre cómo gestionar las etiquetas de un bucket, visite GitHub.

  • Para obtener más información sobre la operación de API que permite establecer etiquetas de bucket, consulte PutBucketTags.

  • Para obtener más información sobre la operación de API que permite obtener etiquetas de bucket, consulte GetBucketTags.

  • Para obtener más información sobre la operación de API que permite eliminar etiquetas de bucket, consulte DeleteBucketTags.