列出存储桶标签

检索 Cloud Storage 存储桶的标签。

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name, gcs::Fields("labels"));
  if (!bucket_metadata) throw std::move(bucket_metadata).status();

  if (bucket_metadata->labels().empty()) {
    std::cout << "The bucket " << bucket_name << " has no labels set.\n";
    return;
  }

  std::cout << "The labels for bucket " << bucket_name << " are:";
  for (auto const& kv : bucket_metadata->labels()) {
    std::cout << "\n  " << kv.first << ": " << kv.second;
  }
  std::cout << "\n";
}

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Storage\StorageClient;

/**
 * Prints a list of a bucket's lables.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_bucket_labels(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $info = $bucket->info();
    if (isset($info['labels'])) {
        foreach ($info['labels'] as $labelKey => $labelValue) {
            printf('%s: %s' . PHP_EOL, $labelKey, $labelValue);
        }
    }
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import pprint

from google.cloud import storage


def get_bucket_labels(bucket_name):
    """Prints out a bucket's labels."""
    # bucket_name = 'your-bucket-name'
    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)

    labels = bucket.labels
    pprint.pprint(labels)

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器