Você pode adicionar, consultar e excluir tags em um bucket usando o OSS SDK for Python 2.0.
Observações
O código de exemplo deste tópico usa o ID da região
cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, você usa um endpoint público para acessar os recursos de um bucket. Para acessar os recursos do bucket a partir de outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para obter mais informações sobre as regiões e os endpoints do OSS, consulte Regiões e endpoints.Neste tópico, você obtém as credenciais de acesso a partir de variáveis de ambiente. Para obter mais informações sobre como configurar as credenciais de acesso, consulte Configurar credenciais de acesso.
Código de exemplo
Configurar tags de um bucket
O código de exemplo a seguir configura as tags de um 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()
Consultar as tags de um bucket
O código de exemplo a seguir consulta as tags de um 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()
Excluir as tags de um 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()