Todos los productos
Search
Centro de documentos

Object Storage Service:Configure y gestione el etiquetado de buckets con OSS SDK for Python 2.0

Última actualización: Sep 22, 2026

Con OSS SDK for Python 2.0, puede agregar, consultar y eliminar etiquetas en un bucket.

Notas

  • El código de ejemplo de este tema utiliza el identificador de región cn-hangzhou, que corresponde a la región China (Hangzhou). De forma predeterminada, se usa un endpoint público para acceder a los recursos de un bucket. Si necesita acceder a los recursos del bucket desde otros servicios de Alibaba Cloud ubicados en la misma región que el bucket, 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 de variables de entorno. Para saber cómo configurar las credenciales de acceso, consulte Configure access credentials.

Código de ejemplo

Configure tags for a bucket

A continuación se muestra el código de ejemplo para configurar etiquetas en un bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser for parsing parameters from the command line.
parser = argparse.ArgumentParser(description="put bucket tags sample")

# (Required) Specify the region parameter, which specifies the region in which the bucket is located. 
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# (Required) Specify the --bucket parameter, which specifies the name of the bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# (Optional) Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the command-line parameters.
    args = parser.parse_args()

    # Load access credentials (AccessKey ID and AccessKey secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Specify the credential provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Call the put_bucket_tags method to configure tags for the bucket.
    result = client.put_bucket_tags(
        oss.PutBucketTagsRequest(
            bucket=args.bucket,  # The name of the bucket.
            tagging=oss.Tagging(  # Create a tag set.
                tag_set=oss.TagSet(  # The tag set contains multiple tags.
                    tags=[  # Define a list of tags.
                        oss.Tag(  # The first tag.
                            key='test_key',  # The tag key.
                            value='test_value',  # The tag value.
                        ),
                        oss.Tag(  # The second tag.
                            key='test_key2',  # The tag key.
                            value='test_value2',  # The tag value.
                        ),
                    ],
                ),
            ),
        )
    )

    # Display the HTTP status code of the operation and request ID.
    print(f'status code: {result.status_code}, '  # The HTTP status code, which indicates whether the request succeeded.
          f'request id: {result.request_id}')    # The request ID, which is used to debug or trace a request.

if __name__ == "__main__":
    # Specify the entry points in the main function of the script when the script is directly run.
    main()

Query the tags of a bucket

A continuación se muestra el código de ejemplo para consultar las etiquetas de un bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser for parsing parameters from the command line.
parser = argparse.ArgumentParser(description="get bucket tags sample")

# (Required) Specify the region parameter, which specifies the region in which the bucket is located. 
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# (Required) Specify the --bucket parameter, which specifies the name of the bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# (Optional) Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the command-line parameters.
    args = parser.parse_args()

    # Load access credentials (AccessKey ID and AccessKey secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Specify the credential provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located.
    cfg.region = args.region

    # Modify the endpoint parameter if a custom endpoint is provided.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Call the get_bucket_tags method to query the tags of the bucket.
    result = client.get_bucket_tags(
        oss.GetBucketTagsRequest(
            bucket=args.bucket,  # The name of the bucket.
        )
    )

    # Display the HTTP status code, request ID and tags.
    print(f'status code: {result.status_code}, '  # The HTTP status code, which indicates whether the request succeeded.
          f'request id: {result.request_id}, '   # The request ID, which is used to debug or trace a request.
          f'tagging: {result.tagging}')         # Information about the tag set.

    # If the returned tag set contains tags, iterate through and output the key-value pairs of each tag.
    if result.tagging.tag_set.tags:  # Check whether tags exist.
        for r in result.tagging.tag_set.tags:  # Traverse the set of tags.
            print(f'result: key: {r.key}, value: {r.value}') # Output the key and value of each tag.

if __name__ == "__main__":
    # Specify the entry points in the main function of the script when the script is directly run.
    main()

Delete the tags of a bucket

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser for parsing parameters from the command line.
parser = argparse.ArgumentParser(description="delete bucket tags sample")

# (Required) Specify the region parameter, which specifies the region in which the bucket is located. 
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# (Required) Specify the --bucket parameter, which specifies the name of the bucket.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# (Optional) Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the command-line parameters.
    args = parser.parse_args()

    # Load access credentials (AccessKey ID and AccessKey secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Specify the credential provider.
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located.
    cfg.region = args.region

    # Modify the endpoint parameter if a custom endpoint is provided.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Call the delete_bucket_tags method to delete all tags of the bucket.
    result = client.delete_bucket_tags(
        oss.DeleteBucketTagsRequest(
            bucket=args.bucket,  # The name of the bucket.
        )
    )

    # Display the HTTP status code of the operation and request ID.
    print(f'status code: {result.status_code}, '  # The HTTP status code, which indicates whether the request succeeded.
          f'request id: {result.request_id}')    # The request ID, which is used to debug or trace a request.

if __name__ == "__main__":
    # Specify the entry points in the main function of the script when the script is directly run.
    main()