Utilizza i pagamenti a carico del richiedente

Overview

In questa pagina viene descritto come abilitare e disabilitare Pagamenti a carico del richiedente e come verificare se i pagamenti a carico del richiedente sono abilitati in un bucket.

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per l'impostazione e la gestione dei pagamenti a carico del richiedente, chiedi all'amministratore di concederti il ruolo Amministratore archiviazione (roles.storage.Admin) per il progetto che contiene il bucket.

Questo ruolo contiene le autorizzazioni necessarie per impostare e gestire i pagamenti a carico del richiedente. Per visualizzare esattamente le autorizzazioni richieste, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

  • storage.buckets.get
  • storage.buckets.update
  • resourcemanager.projects.createBillingAssignment
    • Questa autorizzazione è necessaria solo se non hai un account di fatturazione da utilizzare quando disattivi i pagamenti a carico del richiedente. Per maggiori informazioni, consulta Requisiti di utilizzo e accesso.

Potresti anche riuscire a ottenere queste autorizzazioni con altri ruoli predefiniti o ruoli personalizzati.

Per istruzioni sulla concessione dei ruoli nei progetti, consulta Concedere o revocare un ruolo.

Impostare i pagamenti a carico del richiedente

Per abilitare o disabilitare i pagamenti a carico del richiedente in un bucket:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, trova il bucket da impostare e individua la colonna Requester pays (Pagamenti a carico del richiedente).

    Il valore nella colonna indica lo stato attuale dei pagamenti a carico del richiedente per quel bucket.

  3. Fai clic sullo stato attuale dei pagamenti a carico del richiedente per il bucket.

  4. Nella finestra visualizzata, fai clic su Attiva o Disattiva, a seconda dello stato che vuoi impostare per Pagamenti a carico del richiedente.

Se questa opzione è abilitata, un fumetto verde e la dicitura On vengono visualizzati nella colonna Pagamenti a carico del richiedente per il bucket. Quando questa opzione è disattivata, nella colonna vengono visualizzati un fumetto grigio e la dicitura Off.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni Cloud Storage non riuscite nella console Google Cloud, consulta la pagina Risoluzione dei problemi.

Riga di comando

Utilizza il comando gcloud storage buckets update con il flag appropriato:

gcloud storage buckets update gs://BUCKET_NAME FLAG

Dove:

  • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

  • FLAG è --requester-pays per attivare i pagamenti a carico del richiedente o --no-requester-pays per disattivarlo.

Se l'esito è positivo, la risposta è simile al seguente esempio:

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

Librerie client

C++

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i pagamenti a carico del richiedente in un bucket:

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

L'esempio seguente disabilita i pagamenti a carico del richiedente in un bucket:

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#

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i pagamenti a carico del richiedente in un bucket:


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;
    }
}

L'esempio seguente disabilita i pagamenti a carico del richiedente su un 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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i pagamenti a carico del richiedente in un bucket:

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
}

L'esempio seguente disabilita i pagamenti a carico del richiedente su un bucket:

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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i pagamenti a carico del richiedente in un bucket:

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

L'esempio seguente disabilita i pagamenti a carico del richiedente in un bucket:

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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i pagamenti a carico del richiedente in un bucket:

/**
 * 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);

L'esempio seguente disabilita i pagamenti a carico del richiedente su un bucket:


/**
 * 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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i pagamenti a carico del richiedente in un bucket:

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

L'esempio seguente disabilita i pagamenti a carico del richiedente in un bucket:

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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i pagamenti a carico del richiedente in un bucket:

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

L'esempio seguente disabilita i pagamenti a carico del richiedente in un bucket:

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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i pagamenti a carico del richiedente in un bucket:

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

L'esempio seguente disabilita i pagamenti a carico del richiedente in un bucket:

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. Installa e inizializzatogcloud CLI per generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file JSON contenente le seguenti informazioni:

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

    Dove STATE è true o false.

  3. Utilizza cURL per chiamare l'API JSON con una richiesta PATCH bucket:

    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"

    Dove:

    • JSON_FILE_NAME è il percorso del file JSON creato al passaggio 2.
    • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

API XML

  1. Installa e inizializzatogcloud CLI per generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file XML che contenga le seguenti informazioni:

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

    Dove STATE è Enabled o Disabled.

  3. Utilizza cURL per chiamare l'API XML con una richiesta PUT bucket e il parametro della stringa di query billing:

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

    Dove:

    • XML_FILE_NAME è il percorso del file XML creato al passaggio 2.
    • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

Verificare se l'opzione Pagamenti a carico del richiedente è abilitata

Per verificare se la funzionalità Pagamenti a carico del richiedente è abilitata in un bucket:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, lo stato Pagamenti a carico del richiedente di ciascun bucket è riportato nella colonna Pagamenti a carico del richiedente.

Se attivata, lo stato è verde e viene visualizzata la parola On.

Riga di comando

Utilizza il comando gcloud storage buckets describe con il flag --format:

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

Dove BUCKET_NAME è il nome del bucket di cui vuoi visualizzare lo stato. Ad esempio, my-bucket.

Se l'esito è positivo, la risposta è simile al seguente esempio:

requester_pays: true

Librerie client

C++

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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#

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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. Installa e inizializzatogcloud CLI per generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Utilizza cURL per chiamare l'API JSON con una richiesta GET bucket:

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

    Dove BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

API XML

  1. Installa e inizializzatogcloud CLI per generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Utilizza cURL per chiamare l'API XML con una richiesta GET bucket e il parametro della stringa di query billing:

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

    Dove BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

Bucket per i pagamenti a carico del richiedente dell'accesso

L'esempio seguente mostra come includere un progetto di fatturazione in modo da poter scaricare un oggetto archiviato in un bucket Pagamenti a carico del richiedente. Utilizza una procedura simile per eseguire altre richieste sul bucket per i pagamenti a carico del richiedente o sugli oggetti al suo interno. Per le considerazioni sui prerequisiti, consulta i Requisiti di accesso a pagamento a carico del richiedente.

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket che contiene l'oggetto da scaricare.

  3. Nella finestra visualizzata, utilizza il menu a discesa per selezionare un progetto per la fatturazione.

  4. Seleziona la casella di controllo per confermare di avere l'autorizzazione a utilizzare il progetto selezionato per la fatturazione.

  5. Fai clic su Salva.

  6. Scarica l'oggetto come faresti normalmente.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni Cloud Storage non riuscite nella console Google Cloud, consulta la pagina Risoluzione dei problemi.

Riga di comando

Utilizza il flag --billing-project nella richiesta:

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

Dove:

  • BUCKET_NAME è il nome del bucket contenente l'oggetto che stai scaricando. Ad esempio, my-bucket.
  • OBJECT_NAME è il nome dell'oggetto che stai scaricando. Ad esempio, pets/dog.png.
  • SAVE_TO_LOCATION è il percorso locale in cui salvi l'oggetto. Ad esempio, Desktop/Images.
  • PROJECT_IDENTIFIER è l'ID o il numero del progetto da fatturare. Ad esempio, my-project.

Librerie client

C++

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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#

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


/**
 * 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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione su Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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. Installa e inizializzatogcloud CLI per generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Nella richiesta, includi il parametro della stringa di query userProject impostato sull'ID del progetto da fatturare:

    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"

    Dove:

    • SAVE_TO_LOCATION è la posizione in cui vuoi salvare l'oggetto. Ad esempio, Desktop/dog.png.
    • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.
    • OBJECT_NAME è il nome con codifica URL dell'oggetto che vuoi scaricare. Ad esempio, pets/dog.png, con codifica URL pets%2Fdog.png.
    • PROJECT_IDENTIFIER è l'ID o il numero del progetto da fatturare. Ad esempio, my-project.

API XML

  1. Installa e inizializzatogcloud CLI per generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Nella richiesta, includi l'intestazione x-goog-user-project impostata sull'ID del progetto da fatturare:

    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"

    Dove:

    • PROJECT_ID è l'ID del progetto da fatturare. Ad esempio, my-project.
    • SAVE_TO_LOCATION è la posizione in cui vuoi salvare l'oggetto. Ad esempio, Desktop/dog.png.
    • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.
    • OBJECT_NAME è il nome con codifica URL dell'oggetto che vuoi scaricare. Ad esempio, pets/dog.png, con codifica URL pets%2Fdog.png.

Passaggi successivi