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

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

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

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

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 Functions इंस्टेंस पर मौजूद, कुछ समय के लिए रहने वाली डायरेक्ट्री में फ़ाइल डाउनलोड करें. इस जगह पर, ज़रूरत के हिसाब से फ़ाइल को प्रोसेस किया जा सकता है. इसके बाद, Cloud Storage में उसे अपलोड किया जा सकता है. एसिंक्रोनस टास्क करते समय, पक्का करें कि आपके कॉलबैक में JavaScript का प्रॉमिस प्रॉमिस हो.

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 में अपलोड कर दिया जाता है.