הגדרת התראות Pub/Sub ל-Cloud Storage

סקירה כללית

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

לפני שמתחילים

לפני שמשתמשים בתכונה הזו, צריך לבצע את ההוראות הבאות.

הפעלת Pub/Sub API

להפעיל את ממשק ה-API של Pub/Sub בשביל הפרויקט שיקבל התראות.

להפעלת ה-API

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

כדי לקבל את ההרשאות שנדרשות להגדרה ולצפייה בהתראות Pub/Sub עבור באקט, צריך לבקש מהאדמין להקצות לכם את התפקידים הבאים: התפקידים המוגדרים מראש האלה כוללים את ההרשאות שנדרשות להגדרת התראות ב-Pub/Sub ולצפייה בהן.

  • תפקיד אדמין אחסון (roles/storage.admin) בקטגוריה שרוצים להגדיר עבורה התראות Pub/Sub

  • התפקיד אדמין ב-Pub/Sub‏ (roles/pubsub.admin) בפרויקט שבו רוצים לקבל התראות Pub/Sub

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

במאמר הגדרה וניהול של מדיניות IAM בקטגוריות מוסבר איך להעניק תפקידים בקטגוריות. במאמר שליטה בגישה מוסבר איך להקצות תפקידים בפרויקטים ואיך להגדיר בקרת גישה לנושאים ולמינויים.

מוודאים שיש לכם נושא Pub/Sub קיים

אם עדיין לא עשיתם זאת, צרו נושא Pub/Sub שאליו אתם רוצים לשלוח התראות. אם אתם מתכננים להשתמש ב-Google Cloud CLI או ב-Terraform כדי לבצע את ההוראות שבדף הזה, אתם לא צריכים לבצע את השלב הזה.

הקצאת התפקיד הנדרש לסוכן השירות של הפרויקט

אתם לא צריכים לבצע את השלבים הבאים אם אתם מתכננים להשתמש ב-Google Cloud CLI או ב-Terraform כדי לבצע את ההוראות שבדף הזה.

  1. לקבל את כתובת האימייל של סוכן השירות שמשויך לפרויקט שמכיל את הקטגוריה של Cloud Storage.

  2. נותנים לסוכן השירות את התפקיד 'פרסום הודעות ב-Pub/Sub' (roles/pubsub.publisher) בנושא הרלוונטי ב-Pub/Sub. במאמר שליטה בגישה מוסבר איך להעניק תפקידים לנושאים.

החלת הגדרה של התראה

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

המסוף

אי אפשר לנהל את ההתראות של Pub/Sub באמצעות מסוףCloud de Confiance . במקום זאת, צריך להשתמש ב-CLI של gcloud או באחת מספריות הלקוח הזמינות.

שורת הפקודה

משתמשים בפקודה gcloud storage buckets notifications create:

gcloud storage buckets notifications create gs://BUCKET_NAME --topic=TOPIC_NAME

כאשר:

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

  • TOPIC_NAME הוא הנושא Pub/Sub שאליו צריך לשלוח את ההתראות. אם תציינו נושא שלא קיים בפרויקט שלכם, הפקודה תיצור בשבילכם נושא.

כדי לשלוח התראות לקבוצת משנה של אירועים, צריך לכלול את הדגל --event-types.

ספריות לקוח

C++

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& topic_name) {
  StatusOr<gcs::NotificationMetadata> notification =
      client.CreateNotification(bucket_name, topic_name,
                                gcs::NotificationMetadata());
  if (!notification) throw std::move(notification).status();

  std::cout << "Successfully created notification " << notification->id()
            << " for bucket " << bucket_name << "\n";
  std::cout << "Full details for the notification:\n"
            << *notification << "\n";
}

C#

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.


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

public class CreatePubSubNotificationSample
{
    public Notification CreatePubSubNotification(
        string bucketName = "your-unique-bucket-name",
        string topic = "my-topic")
    {
        StorageClient storage = StorageClient.Create();
        Notification notification = new Notification
        {
            Topic = topic,
            PayloadFormat = "JSON_API_V1"
        };

        Notification createdNotification = storage.CreateNotification(bucketName, notification);
        Console.WriteLine("Notification subscription created with ID: " + createdNotification.Id + " for bucket name " + bucketName);
        return createdNotification;
    }
}

Go

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

import (
	"context"
	"fmt"
	"io"

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

// createBucketNotification creates a notification configuration for a bucket.
func createBucketNotification(w io.Writer, projectID, bucketName, topic string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	// topic := "topic-name"

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	notification := storage.Notification{
		TopicID:        topic,
		TopicProjectID: projectID,
		PayloadFormat:  storage.JSONPayload,
	}

	createdNotification, err := client.Bucket(bucketName).AddNotification(ctx, &notification)
	if err != nil {
		return fmt.Errorf("Bucket.AddNotification: %w", err)
	}
	fmt.Fprintf(w, "Successfully created notification with ID %s for bucket %s.\n", createdNotification.ID, bucketName)
	return nil
}

Java

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

import com.google.cloud.storage.Notification;
import com.google.cloud.storage.NotificationInfo;
import com.google.cloud.storage.NotificationInfo.EventType;
import com.google.cloud.storage.NotificationInfo.PayloadFormat;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class CreateBucketPubSubNotification {

  public static void createBucketPubSubNotification(
      String bucketName,
      String topicName,
      Map<String, String> customAttributes,
      EventType[] eventTypes,
      String objectNamePrefix,
      PayloadFormat payloadFormat) {
    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The name of the topic you would like to create a notification for
    // String topicName = "projects/{your-project}/topics/{your-topic}";

    // Any custom attributes
    // Map<String, String> customAttributes = Map.of("label", "value");

    // The object name prefix for which this notification configuration applies
    // String objectNamePrefix = "blob-";

    // Desired content of the Payload
    // PayloadFormat payloadFormat = PayloadFormat.JSON_API_V1.JSON_API_V1;

    Storage storage = StorageOptions.newBuilder().build().getService();
    NotificationInfo notificationInfo =
        NotificationInfo.newBuilder(topicName)
            .setCustomAttributes(customAttributes)
            .setEventTypes(eventTypes)
            .setObjectNamePrefix(objectNamePrefix)
            .setPayloadFormat(payloadFormat)
            .build();
    Notification notification = storage.createNotification(bucketName, notificationInfo);
    String topic = notification.getTopic();
    System.out.println("Successfully created notification for topic " + topic);
  }
}

Node.js

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

// The name of a topic
// const topic = 'my-topic';

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

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

async function createNotification() {
  // Creates a notification
  await storage.bucket(bucketName).createNotification(topic);

  console.log('Notification subscription created.');
}

createNotification().catch(console.error);

PHP

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי ליצור הגדרה של התראה לקטגוריה באמצעות PHP, קראו את מאמרי העזרה של ספריית הלקוח של Google Cloud.

Python

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

from google.cloud import storage


def create_bucket_notifications(bucket_name, topic_name):
    """Creates a notification configuration for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The name of a topic
    # topic_name = "your-topic-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    notification = bucket.notification(topic_name=topic_name)
    notification.create()

    print(f"Successfully created notification with ID {notification.notification_id} for bucket {bucket_name}")

Ruby

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

require "google/cloud/storage"

def create_bucket_notifications bucket_name:, topic_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of the pubsub topic
  # topic_name = "your-unique-topic-name"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name
  notification = bucket.create_notification topic_name

  puts "Successfully created notification with ID #{notification.id} for bucket #{bucket_name}"
end

Terraform

אתם יכולים להשתמש במשאב של Terraform כדי להוסיף הגדרה של התראה לקטגוריה.

// Create a Pub/Sub notification.
resource "google_storage_notification" "notification" {
  provider       = google-beta
  bucket         = google_storage_bucket.bucket.name
  payload_format = "JSON_API_V1"
  topic          = google_pubsub_topic.topic.id
  depends_on     = [google_pubsub_topic_iam_binding.binding]
}

// Enable notifications by giving the correct IAM permission to the unique service account.
data "google_storage_project_service_account" "gcs_account" {
  provider = google-beta
}

// Create a Pub/Sub topic.
resource "google_pubsub_topic_iam_binding" "binding" {
  provider = google-beta
  topic    = google_pubsub_topic.topic.id
  role     = "roles/pubsub.publisher"
  members  = ["serviceAccount:${data.google_storage_project_service_account.gcs_account.email_address}"]
}

resource "random_id" "bucket_prefix" {
  byte_length = 8
}

// Create a new storage bucket.
resource "google_storage_bucket" "bucket" {
  name                        = "${random_id.bucket_prefix.hex}-example-bucket-name"
  provider                    = google-beta
  location                    = "US"
  uniform_bucket_level_access = true
}

resource "google_pubsub_topic" "topic" {
  name     = "your_topic_name"
  provider = google-beta
}

ממשקי API ל-REST

API ל-JSON

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

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

    {
      "topic": "projects/PROJECT_ID/topics/TOPIC_NAME",
      "payload_format": "JSON_API_V1"
    }

    כאשר:

    • PROJECT_ID הוא המזהה של הפרויקט שמשויך לנושא Pub/Sub שאליו רוצים לשלוח התראות. למשל, my-pet-project.

    • TOPIC_NAME הוא הנושא Pub/Sub שאליו צריך לשלוח את ההתראות. לדוגמה, my-topic.

    כדי לשלוח התראות לקבוצת משנה של אירועים, צריך לכלול את השדה event_types בגוף הבקשה ב-JSON.

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

    curl -X POST --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.s3nsapis.fr/storage/v1/b/BUCKET_NAME/notificationConfigs"

    כאשר:

    • JSON_FILE_NAME הוא הנתיב לקובץ שיצרתם בשלב 2.

    • BUCKET_NAME הוא שם הקטגוריה שרוצים שהמערכת תיצור התראות בשבילה. למשל, my-bucket.

‫API בפורמט XML

אי אפשר לנהל את ההתראות של Pub/Sub באמצעות API בפורמט XML.

אחזור הגדרה של התראה

כדי לאחזר הגדרה ספציפית של התראה שמשויכת לקטגוריה שלכם:

המסוף

אי אפשר לנהל את ההתראות של Pub/Sub באמצעות מסוףCloud de Confiance . במקום זאת, צריך להשתמש ב-Google Cloud CLI או באחת מספריות הלקוח הזמינות.

שורת הפקודה

משתמשים בפקודה gcloud storage buckets notifications describe:

gcloud storage buckets notifications describe projects/_/buckets/BUCKET_NAME/notificationConfigs/NOTIFICATION_ID

כאשר:

  • BUCKET_NAME הוא שם הקטגוריה שרוצים לאחזר את הגדרת ההתראה שלה. לדוגמה, my-bucket.

  • NOTIFICATION_ID הוא המספר המזהה של ההגדרה הרלוונטית. לדוגמה, 5.

אם הפעולה בוצעה ללא שגיאות, התשובה נראית דומה לדוגמה הבאה:

etag: '132'
id: '132'
kind: storage#notification
payload_format: JSON_API_V1
selfLink: https://www.s3nsapis.fr/storage/v1/b/my-bucket/notificationConfigs/132
topic: //pubsub.googleapis.com/projects/my-project/topics/my-bucket

ספריות לקוח

C++

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& notification_id) {
  StatusOr<gcs::NotificationMetadata> notification =
      client.GetNotification(bucket_name, notification_id);
  if (!notification) throw std::move(notification).status();

  std::cout << "Notification " << notification->id() << " for bucket "
            << bucket_name << "\n";
  if (notification->object_name_prefix().empty()) {
    std::cout << "This notification is sent for all objects in the bucket\n";
  } else {
    std::cout << "This notification is sent only for objects starting with"
              << " the prefix " << notification->object_name_prefix() << "\n";
  }
  std::cout << "Full details for the notification:\n"
            << *notification << "\n";
}

C#

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.


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

public class GetPubSubNotificationSample
{
    public Notification GetPubSubNotification(
        string bucketName = "your-unique-bucket-name",
        string notificationId = "notificationId")
    {
        StorageClient storage = StorageClient.Create();
        Notification notification = storage.GetNotification(bucketName, notificationId);

        Console.WriteLine("ID: " + notification.Id);
        Console.WriteLine("Topic: " + notification.Topic);
        Console.WriteLine("EventTypes: " + notification.EventTypes);
        Console.WriteLine("CustomAttributes: " + notification.CustomAttributes);
        Console.WriteLine("PayloadFormat: " + notification.PayloadFormat);
        Console.WriteLine("ObjectNamePrefix: " + notification.ObjectNamePrefix);
        Console.WriteLine("ETag: " + notification.ETag);
        Console.WriteLine("SelfLink: " + notification.SelfLink);
        Console.WriteLine("Kind: " + notification.Kind);

        return notification;
    }
}

Go

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

import (
	"context"
	"fmt"
	"io"

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

// printPubsubBucketNotification gets a notification configuration for a bucket.
func printPubsubBucketNotification(w io.Writer, bucketName, notificationID string) error {
	// bucketName := "bucket-name"
	// notificationID := "notification-id"

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	notifications, err := client.Bucket(bucketName).Notifications(ctx)
	if err != nil {
		return fmt.Errorf("Bucket.Notifications: %w", err)
	}

	n := notifications[notificationID]
	fmt.Fprintf(w, "Notification: %+v", n)

	return nil
}

Java

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

public class PrintPubSubNotification {

  public static void printPubSubNotification(String bucketName, String notificationId) {
    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The Pub/Sub topic you would like to find
    // String notificationId = "your-unique-notification-id"

    Storage storage = StorageOptions.newBuilder().build().getService();
    Notification notification = storage.getNotification(bucketName, notificationId);
    System.out.println(
        "Found notification " + notification.getTopic() + " for bucket " + bucketName);
  }
}

Node.js

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

// The ID of the notification
// const notificationId = '1';

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

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

async function getMetadata() {
  // Get the notification metadata
  const [metadata] = await storage
    .bucket(bucketName)
    .notification(notificationId)
    .getMetadata();

  console.log(`ID: ${metadata.id}`);
  console.log(`Topic: ${metadata.topic}`);
  console.log(`Event Types: ${metadata.event_types}`);
  console.log(`Custom Attributes: ${metadata.custom_attributes}`);
  console.log(`Payload Format: ${metadata.payload_format}`);
  console.log(`Object Name Prefix: ${metadata.object_name_prefix}`);
  console.log(`Etag: ${metadata.etag}`);
  console.log(`Self Link: ${metadata.selfLink}`);
  console.log(`Kind: ${metadata.kind}`);
}

getMetadata().catch(console.error);

PHP

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי לקבל הגדרה של התראה לקטגוריה באמצעות PHP, קראו את מאמרי העזרה של ספריית הלקוח של Google Cloud.

Python

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

from google.cloud import storage


def print_pubsub_bucket_notification(bucket_name, notification_id):
    """Gets a notification configuration for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The ID of the notification
    # notification_id = "your-notification-id"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    notification = bucket.get_notification(notification_id)

    print(f"Notification ID: {notification.notification_id}")
    print(f"Topic Name: {notification.topic_name}")
    print(f"Event Types: {notification.event_types}")
    print(f"Custom Attributes: {notification.custom_attributes}")
    print(f"Payload Format: {notification.payload_format}")
    print(f"Blob Name Prefix: {notification.blob_name_prefix}")
    print(f"Etag: {notification.etag}")
    print(f"Self Link: {notification.self_link}")

Ruby

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

require "google/cloud/storage"

def print_pubsub_bucket_notification bucket_name:, notification_id:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your notification configured for the bucket
  # notification_id = "your-notification-id"


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

  puts "Notification ID: #{notification.id}"
  puts "Topic Name: #{notification.topic}"
  puts "Event Types: #{notification.event_types}"
  puts "Kind of Notification: #{notification.kind}"
  puts "Custom Attributes: #{notification.custom_attrs}"
  puts "Payload Format: #{notification.payload}"
  puts "Blob Name Prefix: #{notification.prefix}"
  puts "Self Link: #{notification.api_url}"
end

ממשקי API ל-REST

API ל-JSON

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

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

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.s3nsapis.fr/storage/v1/b/BUCKET_NAME/notificationConfigs/NOTIFICATION_ID"

    כאשר:

    • BUCKET_NAME הוא שם הקטגוריה שרוצים לאחזר את הגדרת ההתראה שלה. למשל, my-bucket.

    • NOTIFICATION_ID הוא המספר המזהה של הגדרת ההתראה שרוצים לאחזר. למשל, 5.

‫API בפורמט XML

אי אפשר לנהל את ההתראות של Pub/Sub באמצעות API בפורמט XML.

הצגה של רשימת הגדרות של התראות לקטגוריה

כדי להציג רשימה של כל הגדרות ההתראות שמשויכות לקטגוריה מסוימת:

המסוף

אי אפשר לנהל את ההתראות של Pub/Sub באמצעות מסוףCloud de Confiance . במקום זאת, צריך להשתמש ב-CLI של gcloud או באחת מספריות הלקוח הזמינות.

שורת הפקודה

משתמשים בפקודה gcloud storage buckets notifications list:

gcloud storage buckets notifications list gs://BUCKET_NAME

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

ספריות לקוח

C++

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<std::vector<gcs::NotificationMetadata>> items =
      client.ListNotifications(bucket_name);
  if (!items) throw std::move(items).status();

  std::cout << "Notifications for bucket=" << bucket_name << "\n";
  for (gcs::NotificationMetadata const& notification : *items) {
    std::cout << notification << "\n";
  }
}

C#

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.


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

public class ListPubSubNotificationSample
{
    public IReadOnlyList<Notification> ListPubSubNotification(string bucketName = "your-unique-bucket-name")
    {
        StorageClient storage = StorageClient.Create();
        IReadOnlyList<Notification> notifications = storage.ListNotifications(bucketName);

        foreach (Notification notification in notifications)
        {
            Console.WriteLine(notification.Id);
        }
        return notifications;
    }
}

Go

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

import (
	"context"
	"fmt"
	"io"

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

// listBucketNotifications lists notification configurations for a bucket.
func listBucketNotifications(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()

	notifications, err := client.Bucket(bucketName).Notifications(ctx)
	if err != nil {
		return fmt.Errorf("Bucket.Notifications: %w", err)
	}

	for nID, n := range notifications {
		fmt.Fprintf(w, "Notification topic %s with ID %s\n", n.TopicID, nID)
	}

	return nil
}

Java

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

import com.google.cloud.storage.Notification;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.List;

public class ListPubSubNotifications {

  public static void listPubSubNotifications(String bucketName) {
    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().build().getService();
    List<Notification> notificationList = storage.listNotifications(bucketName);
    for (Notification notification : notificationList) {
      System.out.println(
          "Found notification " + notification.getTopic() + " for bucket " + bucketName);
    }
  }
}

Node.js

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

/**
 * 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 listNotifications() {
  // Lists notifications in the bucket
  const [notifications] = await storage.bucket(bucketName).getNotifications();

  console.log('Notifications:');
  notifications.forEach(notification => {
    console.log(notification.id);
  });
}

listNotifications().catch(console.error);

PHP

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי להציג רשימת הגדרות של התראות שמשויכות לקטגוריה באמצעות PHP, קראו את מאמרי העזרה של ספריית הלקוח של Google Cloud.

Python

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

from google.cloud import storage


def list_bucket_notifications(bucket_name):
    """Lists notification configurations for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    notifications = bucket.list_notifications()

    for notification in notifications:
        print(f"Notification ID: {notification.notification_id}")

Ruby

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

require "google/cloud/storage"

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

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

  bucket.notifications.each do |notification|
    puts "Notification ID: #{notification.id}"
  end
end

ממשקי API ל-REST

API ל-JSON

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

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

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.s3nsapis.fr/storage/v1/b/BUCKET_NAME/notificationConfigs"

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

‫API בפורמט XML

אי אפשר לנהל את ההתראות של Pub/Sub באמצעות API בפורמט XML.

הסרת הגדרה של התראה

כדי להסיר הגדרת התראה קיימת מהקטגוריה:

המסוף

אי אפשר לנהל את ההתראות של Pub/Sub באמצעות מסוףCloud de Confiance . במקום זאת, צריך להשתמש ב-CLI של gcloud או באחת מספריות הלקוח הזמינות.

שורת הפקודה

משתמשים בפקודה gcloud storage buckets notifications delete:

gcloud storage buckets notifications delete projects/_/buckets/BUCKET_NAME/notificationConfigs/NOTIFICATION_ID

כאשר:

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

  • NOTIFICATION_ID הוא המספר המזהה של ההגדרה שרוצים למחוק. למשל, 5.

אם הפעולה בוצעה ללא שגיאות, התגובה תיראה דומה לדוגמה הבאה:

Completed 1

אחרי השליחה, יכול להיות שיעברו 30 שניות לכל היותר עד שיפסיקו כל ההתראות שהגדרת ההתראה הפעילה.

ספריות לקוח

C++

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& notification_id) {
  google::cloud::Status status =
      client.DeleteNotification(bucket_name, notification_id);
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "Successfully deleted notification " << notification_id
            << " on bucket " << bucket_name << "\n";
}

C#

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.


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

public class DeletePubSubNotificationSample
{
    public void DeletePubSubNotification(
        string bucketName = "your-unique-bucket-name",
        string notificationId = "notificationId")
    {
        StorageClient storage = StorageClient.Create();
        storage.DeleteNotification(bucketName, notificationId);

        Console.WriteLine("Successfully deleted notification with ID " + notificationId + " for bucket " + bucketName);
    }
}

Go

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

import (
	"context"
	"fmt"
	"io"

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

// deleteBucketNotification deletes a notification configuration for a bucket.
func deleteBucketNotification(w io.Writer, bucketName, notificationID string) error {
	// bucketName := "bucket-name"
	// notificationID := "notification-id"

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	bucket := client.Bucket(bucketName)

	if err := bucket.DeleteNotification(ctx, notificationID); err != nil {
		return fmt.Errorf("Bucket.DeleteNotification: %w", err)
	}
	fmt.Fprintf(w, "Successfully deleted notification with ID %s for bucket %s.\n", notificationID, bucketName)
	return nil
}

Java

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

public class DeleteBucketPubSubNotification {

  public static void deleteBucketPubSubNotification(String bucketName, String notificationId) {
    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The NotificationId for the notification you would like to delete
    // String notificationId = "your-unique-notification-id"

    Storage storage = StorageOptions.newBuilder().build().getService();
    boolean success = storage.deleteNotification(bucketName, notificationId);
    if (success) {
      System.out.println("Successfully deleted notification");
    } else {
      System.out.println("Failed to find notification");
    }
  }
}

Node.js

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

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

// The ID of the notification
// const notificationId = '1';

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

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

async function deleteNotification() {
  // Deletes the notification from the bucket
  await storage.bucket(bucketName).notification(notificationId).delete();

  console.log(`Notification ${notificationId} deleted.`);
}

deleteNotification().catch(console.error);

PHP

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי למחוק הגדרה של התראה לקטגוריה באמצעות PHP, קראו את מאמרי העזרה של ספריית הלקוח של Google Cloud.

Python

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

from google.cloud import storage


def delete_bucket_notification(bucket_name, notification_id):
    """Deletes a notification configuration for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The ID of the notification
    # notification_id = "your-notification-id"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    notification = bucket.notification(notification_id=notification_id)
    notification.delete()

    print(f"Successfully deleted notification with ID {notification_id} for bucket {bucket_name}")

Ruby

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

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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

require "google/cloud/storage"

def delete_bucket_notification bucket_name:, notification_id:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your notification configured for the bucket
  # notification_id = "your-notification-id"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name
  notification = bucket.notification notification_id
  notification.delete

  puts "Successfully deleted notification with ID #{notification_id} for bucket #{bucket_name}"
end

Terraform

כדי להסיר את הגדרת ההתראה שיצרתם, מריצים את הפקודה terraform destroy מהתיקייה שמכילה את הקובץ של Terraform.

ממשקי API בארכיטקטורת REST

API ל-JSON

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

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

    curl -X DELETE \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.s3nsapis.fr/storage/v1/b/BUCKET_NAME/notificationConfigs/NOTIFICATION_ID"

    כאשר:

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

    • NOTIFICATION_ID הוא המספר המזהה של הגדרת ההתראה שרוצים למחוק. למשל, 5.

אחרי השליחה, יכול להיות שיעברו 30 שניות לכל היותר עד שיפסיקו כל ההתראות שהגדרת ההתראה הפעילה.

‫API בפורמט XML

אי אפשר לנהל את ההתראות של Pub/Sub באמצעות API בפורמט XML.

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