Cloud Storage के ट्रिगर


आपके पास अपलोड, अपडेट या Cloud Storage में मौजूद फ़ाइलों और फ़ोल्डर को मिटाने की सुविधा मिलती है.

इस पेज में दिए गए उदाहरण, सैंपल फ़ंक्शन पर आधारित हैं. यह फ़ंक्शन, इमेज को ट्रिगर करने पर ट्रिगर होता है फ़ाइलों को Cloud Storage में अपलोड कर दिया जाता है. यह सैंपल फ़ंक्शन दिखाता है कि इवेंट के एट्रिब्यूट कैसे ऐक्सेस करें, Cloud Functions में फ़ाइल कैसे डाउनलोड करें और Cloud Storage इवेंट को मैनेज करने से जुड़ी अन्य बुनियादी बातें जान लें.

ज़रूरी मॉड्यूल इंपोर्ट करें

शुरू करने के लिए, Cloud Storage को मैनेज करने के लिए ज़रूरी मॉड्यूल इंपोर्ट करें इवेंट:

Node.js

 const {onObjectFinalized} = require("firebase-functions/v2/storage");

Python

 from firebase_functions import storage_fn

पूरा सैंपल बनाने के लिए, Firebase एडमिन SDK टूल और इमेज प्रोसेसिंग टूल:

Node.js

 const {initializeApp} = require("firebase-admin/app");
const {getStorage} = require("firebase-admin/storage");
const logger = require("firebase-functions/logger");
const path = require("path");

// library for image resizing
const sharp = require("sharp");

initializeApp();

Python

 import io
import pathlib

from PIL import Image

from firebase_admin import initialize_app

initialize_app()
from firebase_admin import storage

Cloud Storage फ़ंक्शन का स्कोप

अपने कारोबार का दायरा बढ़ाने के लिए, यहां दिए गए पैटर्न का इस्तेमाल करें फ़ंक्शन को किसी Cloud Storage बकेट में जोड़ें और अपनी पसंद के विकल्प सेट करें:

Node.js

// scope handler to a specific bucket, using storage options parameter
export archivedopts = onObjectArchived({ bucket: "myBucket" }, (event) => {
  //…
});

Python

# Scope handler to a specific bucket using storage options parameter
@storage_fn.on_object_archived(bucket="myBucket")
def archived_bucket(event: storage_fn.CloudEvent[storage_fn.StorageObjectData]):
    # ...

इसके उलट, उदाहरण के तौर पर दिया गया थंबनेल जनरेटर फ़ंक्शन, प्रोजेक्ट:

Node.js

exports.generateThumbnail = onObjectFinalized({cpu: 2}, async (event) => {
// ...
});

Python

@storage_fn.on_object_archived()
def generatethumbnail(event: storage_fn.CloudEvent[storage_fn.StorageObjectData]):
    # ...

फ़ंक्शन की जगह सेट करें

इनके बीच मेल नहीं खाता जगहों की वजह से डिप्लॉयमेंट नहीं हो सकता. साथ ही, जगह के बीच की दूरी और फ़ंक्शन की जगह की वजह से, Cloud Storage बकेट की नेटवर्क इंतज़ार का समय. ऐसी स्थितियों से बचने के लिए, फ़ंक्शन की जगह की जानकारी दें, ताकि यह बकेट/ट्रिगर स्थान से इनमें से किसी एक तरीके से मेल खाता है:

  • फ़ंक्शन की जगह और ट्रिगर की जगह एक ही है
  • फ़ंक्शन की जगह, ट्रिगर की जगह के अंदर होती है (जब ट्रिगर की जगह दो या एक से ज़्यादा इलाके)
  • अगर ट्रिगर वाली जगह us-central1 पर सेट है, तो फ़ंक्शन किसी भी जगह पर हो सकता है

Cloud Storage के इवेंट मैनेज करना

Cloud Storage इवेंट का जवाब देने के लिए, ये हैंडलर उपलब्ध हैं:

Node.js

  • onObjectArchived सिर्फ़ तब भेजी जाती है, जब बकेट चालू हो ऑब्जेक्ट का वर्शन होना. इस इवेंट से पता चलता है कि किसी ऑब्जेक्ट का लाइव वर्शन संग्रह किया गया वर्शन है, क्योंकि उसे संग्रहित कर लिया गया था या उसे ओवरराइट हो जाता है.
  • onObjectDeleted यह सूचना तब भेजी जाती है, जब किसी ऑब्जेक्ट को हमेशा के लिए मिटा दिया गया हो. यह इसमें बकेट के हिस्से के तौर पर ओवरराइट किए गए या मिटाए गए ऑब्जेक्ट शामिल होते हैं लाइफ़साइकल कॉन्फ़िगरेशन. बकेट के लिए ऑब्जेक्ट का वर्शन सक्षम है, तो ऑब्जेक्ट को संग्रहित किए जाने पर यह नहीं भेजा जाता है (onArchive देखें), यहां तक कि अगर डेटा को storage.objects.delete तरीके से संग्रहित किया जाता है.
  • onObjectFinalized यह सूचना तब भेजी जाती है, जब नया ऑब्जेक्ट या नई जनरेशन का मौजूदा ऑब्जेक्ट) बकेट में सफलतापूर्वक बनाया गया है. इसमें कॉपी करना शामिल है शामिल हैं. अपलोड न होने से यह इवेंट ट्रिगर नहीं होता.
  • onMetadataUpdated यह सूचना किसी मौजूदा ऑब्जेक्ट के मेटाडेटा में बदलाव होने पर भेजी जाती है.

Python

  • on_object_archived सिर्फ़ तब भेजी जाती है, जब बकेट चालू हो ऑब्जेक्ट का वर्शन होना. इस इवेंट से पता चलता है कि किसी ऑब्जेक्ट का लाइव वर्शन संग्रह किया गया वर्शन है, क्योंकि उसे संग्रहित कर लिया गया था या उसे ओवरराइट हो जाता है.
  • on_object_deleted यह सूचना तब भेजी जाती है, जब किसी ऑब्जेक्ट को हमेशा के लिए मिटा दिया गया हो. यह इसमें बकेट के हिस्से के तौर पर ओवरराइट किए गए या मिटाए गए ऑब्जेक्ट शामिल होते हैं लाइफ़साइकल कॉन्फ़िगरेशन. बकेट के लिए ऑब्जेक्ट का वर्शन सक्षम है, तो ऑब्जेक्ट को संग्रहित किए जाने पर यह नहीं भेजा जाता है (onArchive देखें), यहां तक कि अगर डेटा को storage.objects.delete तरीके से संग्रहित किया जाता है.
  • on_object_finalized यह सूचना तब भेजी जाती है, जब नया ऑब्जेक्ट या नई जनरेशन का मौजूदा ऑब्जेक्ट) बकेट में सफलतापूर्वक बनाया गया है. इसमें कॉपी करना शामिल है शामिल हैं. अपलोड न होने से यह इवेंट ट्रिगर नहीं होता.
  • on_metadata_updated यह सूचना किसी मौजूदा ऑब्जेक्ट के मेटाडेटा में बदलाव होने पर भेजी जाती है.

Cloud Storage ऑब्जेक्ट एट्रिब्यूट को ऐक्सेस करें

Cloud Functions, कई Cloud Storage ऑब्जेक्ट एट्रिब्यूट दिखाता है जैसे कि अपडेट की गई फ़ाइल के लिए, ऑब्जेक्ट का साइज़ और कॉन्टेंट का टाइप. metageneration विशेषता में कोई बदलाव होने पर विशेषता बढ़ा दी जाती है ऑब्जेक्ट का मेटाडेटा. नए ऑब्जेक्ट के लिए, metageneration की वैल्यू 1 है.

Node.js

const fileBucket = event.data.bucket; // Storage bucket containing the file.
const filePath = event.data.name; // File path in the bucket.
const contentType = event.data.contentType; // File content type.

Python

bucket_name = event.data.bucket
file_path = pathlib.PurePath(event.data.name)
content_type = event.data.content_type

थंबनेल जनरेट करने वाला सैंपल, एग्ज़िट का पता लगाने के लिए इनमें से कुछ एट्रिब्यूट का इस्तेमाल करता है ऐसे मामले जिनमें फ़ंक्शन रिटर्न करता है:

Node.js

// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith("image/")) {
  return logger.log("This is not an image.");
}
// Exit if the image is already a thumbnail.
const fileName = path.basename(filePath);
if (fileName.startsWith("thumb_")) {
  return logger.log("Already a Thumbnail.");
}

Python

# Exit if this is triggered on a file that is not an image.
if not content_type or not content_type.startswith("image/"):
    print(f"This is not an image. ({content_type})")
    return

# Exit if the image is already a thumbnail.
if file_path.name.startswith("thumb_"):
    print("Already a thumbnail.")
    return

फ़ाइल डाउनलोड करना, पूरी तरह बदलना, और अपलोड करना

कुछ मामलों में, हो सकता है कि Google से फ़ाइलें डाउनलोड करना ज़रूरी न हो Cloud Storage. हालांकि, मुश्किल टास्क को पूरा करने के लिए, Cloud Storage में सेव की गई किसी फ़ाइल की थंबनेल इमेज, आपको इसे डाउनलोड करना होगा फ़ाइलों को फ़ंक्शन इंस्टेंस में जोड़ देती है—यानी कि एक वर्चुअल मशीन जो आपका कोड.

इमेज प्रोसेसिंग प्रोग्राम के साथ Cloud Functions का इस्तेमाल करना, जैसे कि Node.js के लिए sharp और Python के लिए Pillow, तुम यह कर सकती हो ग्राफ़िकल इमेज फ़ाइलों में हेर-फेर करना. नीचे एक उदाहरण दिया गया है, जिसमें बताया गया है कि अपलोड की गई इमेज फ़ाइल के लिए थंबनेल इमेज बनाएं:

Node.js

/**
 * When an image is uploaded in the Storage bucket,
 * generate a thumbnail automatically using sharp.
 */
exports.generateThumbnail = onObjectFinalized({cpu: 2}, async (event) => {

  const fileBucket = event.data.bucket; // Storage bucket containing the file.
  const filePath = event.data.name; // File path in the bucket.
  const contentType = event.data.contentType; // File content type.

  // Exit if this is triggered on a file that is not an image.
  if (!contentType.startsWith("image/")) {
    return logger.log("This is not an image.");
  }
  // Exit if the image is already a thumbnail.
  const fileName = path.basename(filePath);
  if (fileName.startsWith("thumb_")) {
    return logger.log("Already a Thumbnail.");
  }

  // Download file into memory from bucket.
  const bucket = getStorage().bucket(fileBucket);
  const downloadResponse = await bucket.file(filePath).download();
  const imageBuffer = downloadResponse[0];
  logger.log("Image downloaded!");

  // Generate a thumbnail using sharp.
  const thumbnailBuffer = await sharp(imageBuffer).resize({
    width: 200,
    height: 200,
    withoutEnlargement: true,
  }).toBuffer();
  logger.log("Thumbnail created");

  // Prefix 'thumb_' to file name.
  const thumbFileName = `thumb_${fileName}`;
  const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);

  // Upload the thumbnail.
  const metadata = {contentType: contentType};
  await bucket.file(thumbFilePath).save(thumbnailBuffer, {
    metadata: metadata,
  });
  return logger.log("Thumbnail uploaded!");
});

इस फ़ाइल को कुछ समय के लिए डाउनलोड करें डायरेक्ट्री पर काम करती है. इस जगह पर ये काम किए जा सकते हैं ज़रूरत के हिसाब से फ़ाइल को प्रोसेस करें और फिर Cloud Storage में अपलोड करें. टास्क कब शुरू होगा एसिंक्रोनस ढंग से कार्य करने के लिए, सुनिश्चित करें कि आप अपने कॉलबैक.

Python

@storage_fn.on_object_finalized()
def generatethumbnail(event: storage_fn.CloudEvent[storage_fn.StorageObjectData]):
    """When an image is uploaded in the Storage bucket, generate a thumbnail
    automatically using Pillow."""

    bucket_name = event.data.bucket
    file_path = pathlib.PurePath(event.data.name)
    content_type = event.data.content_type

    # Exit if this is triggered on a file that is not an image.
    if not content_type or not content_type.startswith("image/"):
        print(f"This is not an image. ({content_type})")
        return

    # Exit if the image is already a thumbnail.
    if file_path.name.startswith("thumb_"):
        print("Already a thumbnail.")
        return

    bucket = storage.bucket(bucket_name)

    image_blob = bucket.blob(str(file_path))
    image_bytes = image_blob.download_as_bytes()
    image = Image.open(io.BytesIO(image_bytes))

    image.thumbnail((200, 200))
    thumbnail_io = io.BytesIO()
    image.save(thumbnail_io, format="png")
    thumbnail_path = file_path.parent / pathlib.PurePath(f"thumb_{file_path.stem}.png")
    thumbnail_blob = bucket.blob(str(thumbnail_path))
    thumbnail_blob.upload_from_string(thumbnail_io.getvalue(), content_type="image/png")

इस कोड से अस्थायी डायरेक्ट्री में सेव की गई इमेज के लिए 200x200 का थंबनेल. इसके बाद, इसे अपलोड कर दिया जाता है Cloud Storage पर वापस जाएं.