요청자 지불 사용

개요

이 페이지에서는 요청자 지불 기능을 설정하는 방법을 설명하고, 요청자 지불 기능을 사용 설정한 버킷에 대한 요청을 만드는 예를 제공합니다.

요청자 지불 설정

다음 섹션에서는 요청자 지불을 설정하고 해제하는 방법과 버킷에서 요청자 지불이 사용 설정되었는지 여부를 확인하는 방법을 보여줍니다.

기본 요건

  1. 버킷에 대한 요청자 지불 상태를 제공하고 Google Cloud 콘솔 또는 Google Cloud CLI에서 요청자 지불을 사용 설정 또는 사용 중지하는 데 필요한 storage.buckets.get 권한이 있어야 합니다.

  2. 요청자 지불을 사용 설정하거나 사용 중지할 때는 storage.buckets.update 권한이 있어야 합니다.

  3. 요청자 지불을 사용 중지할 때는 요청에 결제 프로젝트를 포함하거나 resourcemanager.projects.createBillingAssignment 권한이 있어야 합니다. 자세한 내용은 요청자 지불 사용 및 액세스 요구사항을 참조하세요.

권한은 역할을 통해 사용자에게 제공됩니다. 예를 들어 스토리지 관리자 역할이 부여된 사용자는 위의 storage.buckets 권한을 모두 가집니다. 역할은 버킷을 포함하는 프로젝트에 부여될 수 있습니다.

요청자 지불 설정

버킷에서 요청자 지불을 사용 설정 또는 사용 중지하려면 다음 안내를 따르세요.

Console

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 설정하려는 버킷을 찾고 요청자 지불 열을 찾습니다.

    열의 값은 해당 버킷에 대한 요청자 지불의 현재 상태를 나타냅니다.

  3. 원하는 버킷에 대해 요청자 지불의 현재 상태를 클릭합니다.

  4. 표시된 창에서 요청자 지불에 대해 설정하려는 상태에 따라 사용 설정 또는 사용 중지를 클릭합니다.

사용 설정되면 버킷의 요청자 지불 열에 녹색 풍선과 켜기가 나타납니다. 사용 중지되면 열에 회색 풍선과 끄기가 나타납니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

gcloud storage buckets update 명령어를 적절한 플래그와 함께 사용합니다.

gcloud storage buckets update gs://BUCKET_NAME FLAG

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

  • FLAG는 요청자 지불을 사용 설정하기 위한 --requester-pays 또는 사용 중지하기 위한 '--no-requester-pays입니다.

성공하면 다음 예시와 비슷한 응답이 표시됩니다.

Updating gs://my-bucket/...
  Completed 1  

클라이언트 라이브러리

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> metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetBilling(gcs::BucketBilling{true}));
  if (!metadata) throw std::move(metadata).status();

  std::cout << "Billing configuration for bucket " << metadata->name()
            << " is updated. The bucket now";
  if (!metadata->has_billing()) {
    std::cout << " has no billing configuration.\n";
  } else if (metadata->billing().requester_pays) {
    std::cout << " is configured to charge the caller for requests\n";
  } else {
    std::cout << " is configured to charge the project that owns the bucket"
              << " for requests.\n";
  }
}

다음 샘플은 버킷에서 요청자 지불을 사용 중지합니다.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& billed_project) {
  StatusOr<gcs::BucketMetadata> metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetBilling(gcs::BucketBilling{false}),
      gcs::UserProject(billed_project));
  if (!metadata) throw std::move(metadata).status();

  std::cout << "Billing configuration for bucket " << bucket_name
            << " is updated. The bucket now";
  if (!metadata->has_billing()) {
    std::cout << " has no billing configuration.\n";
  } else if (metadata->billing().requester_pays) {
    std::cout << " is configured to charge the caller for requests\n";
  } else {
    std::cout << " is configured to charge the project that owns the bucket"
              << " for requests.\n";
  }
}

C#

자세한 내용은 Cloud Storage C# API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플은 버킷에서 요청자 지불을 사용 설정합니다.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class EnableRequesterPaysSample
{
    public Bucket EnableRequesterPays(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.Billing ??= new Bucket.BillingData();
        bucket.Billing.RequesterPays = true;
        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Requester pays requests have been enabled for bucket {bucketName}.");
        return bucket;
    }
}

다음 샘플은 버킷에서 요청자 지불을 사용 중지합니다.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class DisableRequesterPaysSample
{
    public Bucket DisableRequesterPays(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions
        {
            UserProject = projectId
        });

        bucket.Billing ??= new Bucket.BillingData();
        bucket.Billing.RequesterPays = false;

        bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions
        {
            UserProject = projectId
        });
        Console.WriteLine($"Requester pays disabled for bucket {bucketName}.");
        return bucket;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플은 버킷에서 요청자 지불을 사용 설정합니다.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// enableRequesterPays sets requester pays flag to true.
func enableRequesterPays(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		RequesterPays: true,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Requester pays enabled for bucket %v\n", bucketName)
	return nil
}

다음 샘플은 버킷에서 요청자 지불을 사용 중지합니다.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// disableRequesterPays sets requester pays flag to false.
func disableRequesterPays(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		RequesterPays: false,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Requester pays disabled for bucket %v\n", bucketName)
	return nil
}

Java

자세한 내용은 Cloud Storage Java API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플은 버킷에서 요청자 지불을 사용 설정합니다.

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class EnableRequesterPays {
  public static void enableRequesterPays(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    bucket.toBuilder().setRequesterPays(true).build().update();

    System.out.println("Requester pays enabled for bucket " + bucketName);
  }
}

다음 샘플은 버킷에서 요청자 지불을 사용 중지합니다.

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class DisableRequesterPays {
  public static void disableRequesterPays(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName, Storage.BucketGetOption.userProject(projectId));
    bucket
        .toBuilder()
        .setRequesterPays(false)
        .build()
        .update(Storage.BucketTargetOption.userProject(projectId));

    System.out.println("Requester pays disabled for bucket " + bucketName);
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플은 버킷에서 요청자 지불을 사용 설정합니다.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function enableRequesterPays() {
  await storage.bucket(bucketName).enableRequesterPays();

  console.log(
    `Requester-pays requests have been enabled for bucket ${bucketName}`
  );
}

enableRequesterPays().catch(console.error);

다음 샘플은 버킷에서 요청자 지불을 사용 중지합니다.


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function disableRequesterPays() {
  // Disables requester-pays requests
  await storage.bucket(bucketName).disableRequesterPays();

  console.log(
    `Requester-pays requests have been disabled for bucket ${bucketName}`
  );
}

disableRequesterPays().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플은 버킷에서 요청자 지불을 사용 설정합니다.

use Google\Cloud\Storage\StorageClient;

/**
 * Enable a bucket's requesterpays metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function enable_requester_pays(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'billing' => [
            'requesterPays' => true
        ]
    ]);
    printf('Requester pays has been enabled for %s' . PHP_EOL, $bucketName);
}

다음 샘플은 버킷에서 요청자 지불을 사용 중지합니다.

use Google\Cloud\Storage\StorageClient;

/**
 * Disable a bucket's requesterpays metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function disable_requester_pays(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'billing' => [
            'requesterPays' => false
        ]
    ]);
    printf('Requester pays has been disabled for %s' . PHP_EOL, $bucketName);
}

Python

자세한 내용은 Cloud Storage Python API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플은 버킷에서 요청자 지불을 사용 설정합니다.

from google.cloud import storage

def enable_requester_pays(bucket_name):
    """Enable a bucket's requesterpays metadata"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.requester_pays = True
    bucket.patch()

    print(f"Requester Pays has been enabled for {bucket_name}")

다음 샘플은 버킷에서 요청자 지불을 사용 중지합니다.

from google.cloud import storage

def disable_requester_pays(bucket_name):
    """Disable a bucket's requesterpays metadata"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.requester_pays = False
    bucket.patch()

    print(f"Requester Pays has been disabled for {bucket_name}")

Ruby

자세한 내용은 Cloud Storage Ruby API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플은 버킷에서 요청자 지불을 사용 설정합니다.

def enable_requester_pays bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.requester_pays = true

  puts "Requester pays has been enabled for #{bucket_name}"
end

다음 샘플은 버킷에서 요청자 지불을 사용 중지합니다.

def disable_requester_pays bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.requester_pays = false

  puts "Requester pays has been disabled for #{bucket_name}"
end

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 다음 정보를 포함하는 JSON 파일을 만듭니다.

    {
      "billing": {
        "requesterPays": STATE
      }
    }

    여기서 STATEtrue 또는 false입니다.

  3. cURL을 사용하여 PATCH 버킷 요청으로 JSON API를 호출합니다.

    curl -X PATCH --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    각 항목의 의미는 다음과 같습니다.

    • JSON_FILE_NAME은 2단계에서 만든 JSON 파일의 경로입니다.
    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰의 이름입니다.
    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

XML API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 다음을 정보를 포함하는 XML 파일을 만듭니다.

    <BillingConfiguration>
      <RequesterPays>STATE</RequesterPays>
    </BillingConfiguration>

    여기서 STATEEnabled 또는 Disabled입니다.

  3. cURL을 사용하여 PUT Bucket 요청 및 billing 쿼리 문자열 매개변수로 XML API를 호출합니다.

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?billing"

    각 항목의 의미는 다음과 같습니다.

    • XML_FILE_NAME은 2단계에서 만든 XML 파일의 경로입니다.
    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰의 이름입니다.
    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

요청자 지불의 사용 설정 여부 확인

버킷에서 요청자 지불이 사용 설정되었는지 확인하려면 다음 안내를 따르세요.

Console

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록의 요청자 지불 열에 각 버킷의 요청자 지불 상태가 표시됩니다.

사용 설정된 경우 상태가 녹색이고 켜기라는 단어가 나타납니다.

명령줄

gcloud storage buckets describe 명령어를 --format 플래그와 함께 사용합니다.

gcloud storage buckets describe gs://BUCKET_NAME --format="default(requester_pays)"

여기서 BUCKET_NAME은 상태를 보려는 버킷의 이름입니다. 예를 들면 my-bucket입니다.

성공하면 다음 예시와 비슷한 응답이 표시됩니다.

requester_pays: true

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

  if (!metadata->has_billing()) {
    std::cout
        << "The bucket " << metadata->name() << " does not have a"
        << " billing configuration. The default applies, i.e., the project"
        << " that owns the bucket pays for the requests.\n";
    return;
  }

  if (metadata->billing().requester_pays) {
    std::cout
        << "The bucket " << metadata->name()
        << " is configured to charge the calling project for the requests.\n";
  } else {
    std::cout << "The bucket " << metadata->name()
              << " is configured to charge the project that owns the bucket "
                 "for the requests.\n";
  }
}

C#

자세한 내용은 Cloud Storage C# API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Cloud.Storage.V1;
using System;

public class GetRequesterPaysStatusSample
{
    public bool GetRequesterPaysStatus(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions
        {
            UserProject = projectId
        });
        bool requesterPays = bucket.Billing?.RequesterPays ?? false;
        Console.WriteLine($"RequesterPays: {requesterPays}");
        return requesterPays;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getRequesterPaysStatus gets requester pays status.
func getRequesterPaysStatus(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Is requester pays enabled? %v\n", attrs.RequesterPays)
	return nil
}

Java

자세한 내용은 Cloud Storage Java API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

public class GetRequesterPaysStatus {
  public static void getRequesterPaysStatus(String projectId, String bucketName)
      throws StorageException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket =
        storage.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.BILLING));

    System.out.println("Requester pays status : " + bucket.requesterPays());
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getRequesterPaysStatus() {
  // Gets the requester-pays status of a bucket
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  let status;
  if (metadata && metadata.billing && metadata.billing.requesterPays) {
    status = 'enabled';
  } else {
    status = 'disabled';
  }
  console.log(
    `Requester-pays requests are ${status} for bucket ${bucketName}.`
  );
}

getRequesterPaysStatus().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * Get a bucket's requesterpays metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_requester_pays_status(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucketInformation = $bucket->info();
    $requesterPaysStatus = $bucketInformation['billing']['requesterPays'];
    if ($requesterPaysStatus) {
        printf('Requester Pays is enabled for %s' . PHP_EOL, $bucketName);
    } else {
        printf('Requester Pays is disabled for %s' . PHP_EOL, $bucketName);
    }
}

Python

자세한 내용은 Cloud Storage Python API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import storage

def get_requester_pays_status(bucket_name):
    """Get a bucket's requester pays metadata"""
    # bucket_name = "my-bucket"
    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    requester_pays_status = bucket.requester_pays

    if requester_pays_status:
        print(f"Requester Pays is enabled for {bucket_name}")
    else:
        print(f"Requester Pays is disabled for {bucket_name}")

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET 버킷 요청으로 JSON API를 호출합니다.

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰의 이름입니다.
    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

XML API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET Bucket 요청 및 billing 쿼리 문자열 매개변수로 XML API를 호출합니다.

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?billing"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰의 이름입니다.
    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

요청자 지불 버킷 액세스

다음 예에서는 요청자 지불 버킷에 저장된 객체를 다운로드할 수 있게 결제 프로젝트를 포함하는 방법을 보여줍니다. 비슷한 절차에 따라 요청자 지불 버킷이나 버킷 내 객체에 대한 다른 요청을 수행합니다. 사전 고려사항은 요청자 지불 액세스 요구사항을 참조하세요.

Console

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 다운로드하려는 객체가 포함된 버킷 이름을 클릭합니다.

  3. 나타나는 창에서 드롭다운 메뉴를 사용하여 결제용 프로젝트를 선택합니다.

  4. 선택한 프로젝트를 결제 용도로 사용할 권한이 있는지 확인하는 체크박스를 선택합니다.

  5. 저장을 클릭합니다.

  6. 평소와 같이 객체를 다운로드합니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

요청에 --billing-project 플래그를 사용합니다.

gcloud storage cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION --billing-project=PROJECT_IDENTIFIER

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 다운로드할 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
  • OBJECT_NAME은 다운로드할 객체의 이름입니다. 예를 들면 pets/dog.png입니다.
  • SAVE_TO_LOCATION은 객체를 저장할 로컬 경로입니다. 예를 들면 Desktop/Images입니다.
  • PROJECT_IDENTIFIER는 요금이 청구될 프로젝트의 ID 또는 번호입니다. 예를 들면 my-project입니다.

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& billed_project) {
  gcs::ObjectReadStream stream = client.ReadObject(
      bucket_name, object_name, gcs::UserProject(billed_project));

  std::string line;
  while (std::getline(stream, line, '\n')) {
    std::cout << line << "\n";
  }
  if (stream.bad()) throw google::cloud::Status(stream.status());
}

C#

자세한 내용은 Cloud Storage C# API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class DownloadFileRequesterPaysSample
{
    public void DownloadFileRequesterPays(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name",
        string objectName = "my-file-name",
        string localPath = "my-local-path/my-file-name")
    {
        var storage = StorageClient.Create();
        using var outputFile = File.OpenWrite(localPath);
        storage.DownloadObject(bucketName, objectName, outputFile, new DownloadObjectOptions
        {
            UserProject = projectId
        });
        Console.WriteLine($"Downloaded {objectName} to {localPath} paid by {projectId}.");
    }
}

Go

자세한 내용은 Cloud Storage Go API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// downloadUsingRequesterPays downloads an object using billing project.
func downloadUsingRequesterPays(w io.Writer, bucket, object, billingProjectID string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// billingProjectID := "billing_account_id"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	b := client.Bucket(bucket).UserProject(billingProjectID)
	src := b.Object(object)

	// Open local file.
	f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)
	if err != nil {
		return fmt.Errorf("os.OpenFile: %w", err)
	}

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	rc, err := src.NewReader(ctx)
	if err != nil {
		return fmt.Errorf("Object(%q).NewReader: %w", object, err)
	}
	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %w", err)
	}
	if err := rc.Close(); err != nil {
		return fmt.Errorf("Reader.Close: %w", err)
	}
	fmt.Fprintf(w, "Downloaded using %v as billing project.\n", billingProjectID)
	return nil
}

Java

자세한 내용은 Cloud Storage Java API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.nio.file.Path;

public class DownloadRequesterPaysObject {
  public static void downloadRequesterPaysObject(
      String projectId, String bucketName, String objectName, Path destFilePath) {
    // The project ID to bill
    // String projectId = "my-billable-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The path to which the file should be downloaded
    // Path destFilePath = Paths.get("/local/path/to/file.txt");

    Storage storage = StorageOptions.getDefaultInstance().getService();
    Blob blob =
        storage.get(
            BlobId.of(bucketName, objectName), Storage.BlobGetOption.userProject(projectId));
    blob.downloadTo(destFilePath, Blob.BlobSourceOption.userProject(projectId));

    System.out.println(
        "Object " + objectName + " downloaded to " + destFilePath + " and billed to " + projectId);
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The project ID to bill
// const projectId = 'my-billable-project-id';

// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const srcFileName = 'your-file-name';

// The path to which the file should be downloaded
// const destFileName = '/local/path/to/file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function downloadFileUsingRequesterPays() {
  const options = {
    destination: destFileName,
    userProject: projectId,
  };

  // Downloads the file
  await storage.bucket(bucketName).file(srcFileName).download(options);

  console.log(
    `gs://${bucketName}/${srcFileName} downloaded to ${destFileName} using requester-pays requests`
  );
}

downloadFileUsingRequesterPays().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * Download file using specified project as requester
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 *        (e.g. 'my-project-id')
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $destination The local destination to save the object.
 *        (e.g. '/path/to/your/file')
 */
function download_file_requester_pays(string $projectId, string $bucketName, string $objectName, string $destination): void
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $userProject = true;
    $bucket = $storage->bucket($bucketName, $userProject);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination);
    printf('Downloaded gs://%s/%s to %s using requester-pays requests.' . PHP_EOL,
        $bucketName, $objectName, basename($destination));
}

Python

자세한 내용은 Cloud Storage Python API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import storage

def download_file_requester_pays(
    bucket_name, project_id, source_blob_name, destination_file_name
):
    """Download file using specified project as the requester"""
    # bucket_name = "your-bucket-name"
    # project_id = "your-project-id"
    # source_blob_name = "source-blob-name"
    # destination_file_name = "local-destination-file-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name, user_project=project_id)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {} using a requester-pays request.".format(
            source_blob_name, destination_file_name
        )
    )

Ruby

자세한 내용은 Cloud Storage Ruby API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def download_file_requester_pays bucket_name:, file_name:, local_file_path:
  # The ID of a GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of a GCS object
  # file_name = "your-file-name"

  # The path to which the file should be downloaded
  # local_file_path = "/local/path/to/file.txt"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name, skip_lookup: true, user_project: true
  file    = bucket.file file_name

  file.download local_file_path

  puts "Downloaded #{file.name} using billing project #{storage.project}"
end

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 요금이 청구될 프로젝트의 ID로 설정된 userProject 쿼리 문자열 매개변수를 요청에 포함합니다.

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?alt=media&userProject=PROJECT_IDENTIFIER"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • SAVE_TO_LOCATION은 객체를 저장할 위치입니다. 예를 들면 Desktop/dog.png입니다.
    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • OBJECT_NAME은 다운로드할 객체의 URL 인코딩 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.
    • PROJECT_IDENTIFIER는 요금이 청구될 프로젝트의 ID 또는 번호입니다. 예를 들면 my-project입니다.

XML API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 요금이 청구될 프로젝트의 ID로 설정된 x-goog-user-project 헤더를 요청에 포함합니다.

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-user-project: PROJECT_ID" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • PROJECT_ID는 요금이 청구될 프로젝트의 ID입니다. 예를 들면 my-project입니다.
    • SAVE_TO_LOCATION은 객체를 저장할 위치입니다. 예를 들면 Desktop/dog.png입니다.
    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • OBJECT_NAME은 다운로드할 객체의 URL 인코딩 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

다음 단계