קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
Google Cloud's Pub/Sub הוא אוטובוס הודעות מבוזר גלובלית שניתן להרחבה אוטומטית לפי הצורך.
אפשר להפעיל פונקציה בכל פעם שנשלחת הודעה חדשה Pub/Sub לנושא ספציפי.
ייבוא המודולים הנדרשים
כדי להתחיל, מייבאים את המודולים שנדרשים לטיפול באירועים של Pub/Sub:
@pubsub_fn.on_message_published(topic="topic-name")defhellopubsub(event:pubsub_fn.CloudEvent[pubsub_fn.MessagePublishedData])-> None:"""Log a message using data published to a Pub/Sub topic."""
המטען הייעודי (payload) של ההודעה Pub/Sub נגיש מאובייקט ההודעה שמוחזר לפונקציה. בהודעות עם JSON בגוף ההודעה Pub/Sub, ל-SDK של Firebase ל-Cloud Functions יש מאפיין עזר לפענוח ההודעה. לדוגמה, הנה הודעה שפורסמה עם מטען ייעודי (payload) פשוט של JSON:
אפשר לגשת למטען ייעודי (payload) של נתוני JSON כמו זה באמצעות המאפיין json:
Node.js
// Get the `name` attribute of the PubSub message JSON body.letname=null;try{name=event.data.message.json.name;}catch(e){logger.error("PubSub message was not JSON",e);}
# Get the `name` attribute of the PubSub message JSON body.try:data=event.data.message.jsonexceptValueError:print("PubSub message was not JSON")returnifdataisNone:returnif"name"notindata:print("No 'name' key")returnname=data["name"]
מטענים ייעודיים (payload) אחרים שאינם JSON כלולים בהודעה Pub/Sub כמחרוזות בקידוד base64 באובייקט ההודעה. כדי לקרוא הודעה כמו זו שבהמשך, צריך לפענח את המחרוזת בקידוד base64 כמו שמוצג:
# Get the `name` attribute of the message.if"name"notinevent.data.message.attributes:print("No 'name' attribute")returnname=event.data.message.attributes["name"]
[[["התוכן קל להבנה","easyToUnderstand","thumb-up"],["התוכן עזר לי לפתור בעיה","solvedMyProblem","thumb-up"],["סיבה אחרת","otherUp","thumb-up"]],[["חסרים לי מידע או פרטים","missingTheInformationINeed","thumb-down"],["התוכן מורכב מדי או עם יותר מדי שלבים","tooComplicatedTooManySteps","thumb-down"],["התוכן לא עדכני","outOfDate","thumb-down"],["בעיה בתרגום","translationIssue","thumb-down"],["בעיה בדוגמאות/בקוד","samplesCodeIssue","thumb-down"],["סיבה אחרת","otherDown","thumb-down"]],["עדכון אחרון: 2025-09-06 (שעון UTC)."],[],[],null,["\u003cbr /\u003e\n\nGoogle Cloud's [Pub/Sub](https://cloud.google.com/pubsub/docs/) is a\nglobally distributed message bus that automatically scales as you need it.\nYou can trigger a function whenever a new Pub/Sub message is sent\nto a specific topic.\n\nImport the required modules\n\nTo get started, import the modules required for handling Pub/Sub\nevents: \n\nNode.js \n\n const {onMessagePublished} = require(\"firebase-functions/v2/pubsub\");\n const logger = require(\"firebase-functions/logger\"); \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/pubsub-helloworld/functions/index.js#L19-L20\n\nPython \n\n from firebase_functions import pubsub_fn \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/pubsub-helloworld/functions/main.py#L18-L18\n\nTrigger the function\n\nYou must specify the Pub/Sub topic name that\nyou want to trigger your function, and set the event within the\nevent handler: \n\nNode.js \n\n exports.hellopubsub = onMessagePublished(\"topic-name\", (event) =\u003e { \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/pubsub-helloworld/functions/index.js#L29-L29\n\nPython \n\n @pubsub_fn.on_message_published(topic=\"topic-name\")\n def hellopubsub(event: pubsub_fn.CloudEvent[pubsub_fn.MessagePublishedData]) -\u003e None:\n \"\"\"Log a message using data published to a Pub/Sub topic.\"\"\" \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/pubsub-helloworld/functions/main.py#L24-L26\n\nAccess the pub/sub message payload\n\nThe payload for the Pub/Sub message is accessible from the\nmessage object returned\nto your function. For messages with JSON in the Pub/Sub message\nbody, the Firebase SDK for Cloud Functions has a helper property to decode the message. For\nexample, here is a message published with a simple JSON payload: \n\n gcloud pubsub topics publish topic-name --message '{\"name\":\"Xenia\"}'\n\nYou can access a JSON data payload like this via the\n`json` property: \n\nNode.js \n\n```javascript\n // Get the `name` attribute of the PubSub message JSON body.\n let name = null;\n try {\n name = event.data.message.json.name;\n } catch (e) {\n logger.error(\"PubSub message was not JSON\", e);\n }https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/pubsub-helloworld/functions/index.js#L51-L57\n```\n\nPython \n\n # Get the `name` attribute of the PubSub message JSON body.\n try:\n data = event.data.message.json\n except ValueError:\n print(\"PubSub message was not JSON\")\n return\n if data is None:\n return\n if \"name\" not in data:\n print(\"No 'name' key\")\n return\n name = data[\"name\"] \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/pubsub-helloworld/functions/main.py#L42-L53\n\nOther, non-JSON payloads are contained in the Pub/Sub message as\nbase64 encoded strings in the message object. To read a message like the\nfollowing, you must decode the base64 encoded string as shown: \n\n gcloud pubsub topics publish topic-name --message 'MyMessage'\n\nNode.js \n\n```javascript\n// Decode the PubSub Message body.\nconst message = event.data.message;\nconst messageBody = message.data ?\n Buffer.from(message.data, \"base64\").toString() :\n null;https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/pubsub-helloworld/functions/index.js#L32-L36\n```\n\nPython \n\n # Decode the PubSub message body.\n message_body = base64.b64decode(event.data.message.data) \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/pubsub-helloworld/functions/main.py#L29-L30\n\nAccess message attributes\n\nPub/Sub message can be sent with data attributes set in the\npublish command. For example, you could publish a message with a `name`\nattribute: \n\n gcloud pubsub topics publish topic-name --attribute name=Xenia\n\nYou can read such attributes from the corresponding property of the\nmessage object: \n\nNode.js \n\n```javascript\n// Get the `name` attribute of the message.\nconst name = event.data.message.attributes.name;https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/pubsub-helloworld/functions/index.js#L71-L72\n```\n\nPython \n\n # Get the `name` attribute of the message.\n if \"name\" not in event.data.message.attributes:\n print(\"No 'name' attribute\")\n return\n name = event.data.message.attributes[\"name\"] \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/pubsub-helloworld/functions/main.py#L64-L68"]]