שימוש בתכונה 'מגיש הבקשה משלם'

סקירה כללית

בדף הזה מוסבר איך להפעיל ולהשבית את התכונה מגיש הבקשה משלם, וגם איך לבדוק אם התכונה מופעלת בקטגוריה מסוימת.

התפקידים הנדרשים

כדי לקבל את ההרשאות הנדרשות להגדרה ולניהול של Requester Pays, צריך לבקש מהאדמין להקצות לכם את התפקיד Storage Admin (roles.storage.Admin) בפרויקט שמכיל את הקטגוריה.

התפקיד הזה מכיל את ההרשאות שנדרשות להגדרה ולניהול של בקשות עם תשלום של המבקש. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

  • storage.buckets.get
  • storage.buckets.update
  • resourcemanager.projects.createBillingAssignment
    • ההרשאה הזו נדרשת רק אם אין לכם חשבון לחיוב שבו אתם יכולים להשתמש כשאתם משביתים את התכונה 'המשלם הוא המבקש'. מידע נוסף זמין במאמר בנושא דרישות השימוש והגישה.

יכול להיות שתוכלו לקבל את ההרשאות האלה גם בתפקידים מוגדרים מראש או בתפקידים בהתאמה אישית אחרים.

להוראות על הקצאת תפקידים בפרויקטים, ראו הקצאה או ביטול של תפקיד.

הגדרת 'מגיש הבקשה משלם'

כדי להפעיל או להשבית את 'מגיש הבקשה משלם' בקטגוריה מסוימת:

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, מוצאים את הקטגוריה שרוצים להגדיר ומאתרים את העמודה Requester pays.

    הערך בעמודה מציין את המצב הנוכחי של 'מגיש הבקשה משלם' של הקטגוריה הזו.

  3. לוחצים על המצב הנוכחי של 'מגיש הבקשה משלם' של הקטגוריה.

  4. בחלון שנפתח, לוחצים על Turn on או Turn off בהתאם למצב שרוצים להגדיר ל'מגיש הבקשה משלם'.

כשהתכונה הזו מופעלת, בעמודה Requester pays של הקטגוריה יופיעו בועה ירוקה והמילה On. כשהתכונה הזו מושבתת, יופיעו בעמודה בועה אפורה והמילה Off.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו במסוף Google Cloud .

שורת הפקודה

משתמשים בפקודה 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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מפעילה את 'מגיש הבקשה משלם' בקטגוריה:

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מפעילה את 'מגיש הבקשה משלם' בקטגוריה:


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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מפעילה את 'מגיש הבקשה משלם' בקטגוריה:

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מפעילה את 'מגיש הבקשה משלם' בקטגוריה:

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מפעילה את 'מגיש הבקשה משלם' בקטגוריה:

/**
 * 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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מפעילה את 'מגיש הבקשה משלם' בקטגוריה:

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מפעילה את 'מגיש הבקשה משלם' בקטגוריה:

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

הדוגמה הבאה מפעילה את 'מגיש הבקשה משלם' בקטגוריה:

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

ממשקי API ל-REST

API ל-JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. יוצרים קובץ JSON שמכיל את הפרטים הבאים:

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

    כאשר הערך של STATE הוא true או false.

  3. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשה של קטגוריית PATCH:

    curl -X PATCH --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    כאשר:

    • JSON_FILE_NAME הוא הנתיב לקובץ JSON שיצרתם בשלב 2.
    • BUCKET_NAME הוא שם הקטגוריה הרלוונטית. לדוגמה, my-bucket.

‫API בפורמט XML

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. יוצרים קובץ XML שמכיל את הפרטים הבאים:

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

    כאשר STATE הוא Enabled או Disabled.

  3. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט XML באמצעות בקשה של קטגוריית PUT ופרמטר billing של מחרוזת השאילתה:

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?billing"

    כאשר:

    • XML_FILE_NAME הוא הנתיב לקובץ XML שיצרתם בשלב 2.
    • BUCKET_NAME הוא שם הקטגוריה הרלוונטית. לדוגמה, my-bucket.

איך בודקים אם התכונה 'מגיש הבקשה משלם' מופעלת

כדי לבדוק אם התכונה 'מגיש הבקשה משלם' מופעלת בקטגוריה מסוימת:

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, הסטטוס של 'מגיש הבקשה משלם' של כל קטגוריה מופיע בעמודה Requester Pays.

אם הוא מופעל, הסטטוס יהיה בצבע ירוק ותופיע המילה On.

שורת הפקודה

משתמשים בפקודה 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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

/**
 * 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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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}")

ממשקי API ל-REST

API ל-JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשה של קטגוריית GET:

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    כאשר BUCKET_NAME הוא השם של הקטגוריה הרלוונטית. לדוגמה, my-bucket.

‫API בפורמט XML

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט XML באמצעות בקשה של קטגוריית GET ופרמטר billing של מחרוזת השאילתה:

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?billing"

    כאשר BUCKET_NAME הוא השם של הקטגוריה הרלוונטית. לדוגמה, my-bucket.

גישה לקטגוריות של 'מגיש הבקשה משלם'

הדוגמה הבאה מראה איך לכלול פרויקט לחיוב כדי שתוכלו להוריד אובייקט שמאוחסן בקטגוריה של 'מגיש הבקשה משלם'. צריך לפעול לפי תהליך דומה כדי לבצע בקשות אחרות בקטגוריה של 'מגיש הבקשה משלם' או באובייקטים שנמצאים בה. למידע לגבי דרישות מוקדמות, ראו דרישות הגישה של 'מגיש הבקשה משלם'.

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על שם הקטגוריה שמכילה את האובייקט שרוצים להוריד.

  3. בחלון שמופיע, משתמשים בתפריט הנפתח כדי לבחור פרויקט לחיוב.

  4. מסמנים את התיבה כדי לאשר שאתם מורשים להשתמש בפרויקט שנבחר למטרות חיוב.

  5. לוחצים על Save.

  6. מורידים את האובייקט כרגיל.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו במסוף Google Cloud .

שורת הפקודה

משתמשים בדגל --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 הוא המזהה או המספר של הפרויקט לחיוב. לדוגמה, my-project.

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


/**
 * 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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

ממשקי API ל-REST

API ל-JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. מוסיפים לבקשה שלכם את הפרמטר userProject של מחרוזת השאילתה, מוגדר למזהה הפרויקט לחיוב:

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?alt=media&userProject=PROJECT_IDENTIFIER"

    כאשר:

    • SAVE_TO_LOCATION הוא המיקום שבו רוצים לשמור את האובייקט. לדוגמה, Desktop/dog.png.
    • BUCKET_NAME הוא שם הקטגוריה הרלוונטית. לדוגמה, my-bucket.
    • OBJECT_NAME הוא שם האובייקט שרוצים להוריד, מותאם לקידודי התווים שמתאימים לכתובות URL. לדוגמה, pets/dog.png יותאם לקידודי התווים שמתאימים לכתובות URL באופן הבא: pets%2Fdog.png.
    • PROJECT_IDENTIFIER הוא המזהה או המספר של הפרויקט לחיוב. לדוגמה, my-project.

‫API בפורמט XML

  1. ה-CLI של gcloud מותקן ומופעל, כך שאפשר ליצור אסימון גישה לכותרת Authorization.

  2. מוסיפים בבקשה שלכם את הכותרת x-goog-user-project, מוגדרת למזהה הפרויקט לחיוב:

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "x-goog-user-project: PROJECT_ID" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    כאשר:

    • PROJECT_ID הוא מזהה הפרויקט לחיוב. לדוגמה, my-project.
    • SAVE_TO_LOCATION הוא המיקום שבו רוצים לשמור את האובייקט. לדוגמה, Desktop/dog.png.
    • BUCKET_NAME הוא שם הקטגוריה הרלוונטית. לדוגמה, my-bucket.
    • OBJECT_NAME הוא שם האובייקט שרוצים להוריד, מותאם לקידודי התווים שמתאימים לכתובות URL. לדוגמה, pets/dog.png יותאם לקידודי התווים שמתאימים לכתובות URL באופן הבא: pets%2Fdog.png.

המאמרים הבאים