8000 Adds storage Pub/Sub notification polling tutorial (#875) · TillHaenisch/python-docs-samples@6245c9d · GitHub
[go: up one dir, main page]

Skip to content

Commit 6245c9d

Browse files
BrandonYJon Wayne Parrott
authored andcommitted
Adds storage Pub/Sub notification polling tutorial (GoogleCloudPlatform#875)
1 parent 559c791 commit 6245c9d

File tree

5 files changed

+207
-0
lines changed

5 files changed

+207
-0
lines changed

storage/cloud-client/README.rst

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,45 @@ To run this sample:
232232
-h, --help show this help message and exit
233233
234234
235+
Notification Polling
236+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
237+
238+
239+
240+
To run this sample:
241+
242+
.. code-block:: bash
243+
244+
$ python notification_polling.py
245+
246+
usage: notification_polling.py [-h] [--project PROJECT] subscription
247+
248+
This application demonstrates how to poll for GCS notifications from a Cloud
249+
Pub/Sub subscription, parse the incoming message, and acknowledge the
250+
successful processing of the message. This application will work with any
251+
subscription configured for pull rather than push notifications. If you do not
252+
already have notifications configured, you may consult the docs at
253+
https://cloud.google.com/storage/docs/reporting-changes or follow the steps
254+
below: 1. Activate the Google Cloud Pub/Sub API, if you have not already done
255+
so. https://console.cloud.google.com/flows/enableapi?apiid=pubsub 2. Create a
256+
Google Cloud Storage bucket: $ gsutil mb gs://testbucket 3. Create a Cloud
257+
Pub/Sub topic and publish bucket notifications there: $ gsutil notification
258+
create -f json -t testtopic gs://testbucket 4. Create a subscription for your
259+
new topic: $ gcloud beta pubsub subscriptions create testsubscription
260+
--topic=testtopic 5. Run this program: $ python notification_polling
261+
testsubscription 6. While the program is running, upload and delete some files
262+
in the testbucket bucket (you could use the console or gsutil) and watch as
263+
changes scroll by in the app.
264+
265+
positional arguments:
266+
subscription The ID of the Pub/Sub subscription
267+
268+
optional arguments:
269+
-h, --help show this help message and exit
270+
--project PROJECT The project of the subscription, if not in your default
271+
project
272+
273+
235274
236275
237276
The client library

storage/cloud-client/README.rst.in

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,8 @@ samples:
2424
- name: Customer-Supplied Encryption
2525
file: encryption.py
2626
show_help: true
27+
- name: Notification Polling
28+
file: notification_polling.py
29+
show_help: true
2730

2831
cloud_client_library: true
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2017 Google Inc. All rights reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""This application demonstrates how to poll for GCS notifications from a
18+
Cloud Pub/Sub subscription, parse the incoming message, and acknowledge the
19+
successful processing of the message.
20+
21+
This application will work with any subscription configured for pull rather
22+
than push notifications. If you do not already have notifications configured,
23+
you may consult the docs at
24+
https://cloud.google.com/storage/docs/reporting-changes or follow the steps
25+
below:
26+
27+
1. Activate the Google Cloud Pub/Sub API, if you have not already done so.
28+
https://console.cloud.google.com/flows/enableapi?apiid=pubsub
29+
30+
2. Create a Google Cloud Storage bucket:
31+
$ gsutil mb gs://testbucket
32+
33+
3. Create a Cloud Pub/Sub topic and publish bucket notifications there:
34+
$ gsutil notification create -f json -t testtopic gs://testbucket
35+
36+
4. Create a subscription for your new topic:
37+
$ gcloud beta pubsub subscriptions create testsubscription --topic=testtopic
38+
39+
5. Run this program:
40+
$ python notification_polling testsubscription
41+
42+
6. While the program is running, upload and delete some files in the testbucket
43+
bucket (you could use the console or gsutil) and watch as changes scroll by
44+
in the app.
45+
"""
46+
47+
import argparse
48+
import json
49+
import sys
50+
51+
from google.cloud import pubsub
52+
53+
54+
def summarize(message):
55+
# [START parse_message]
56+
data = message.data
57+
attributes = message.attributes
58+
59+
event_type = attributes['eventType']
60+
bucket_id = attributes['bucketId']
61+
object_id = attributes['objectId']
62+
generation = attributes['objectGeneration']
63+
description = (
64+
'\tEvent type: {event_type}\n'
65+
'\tBucket ID: {bucket_id}\n'
66+
'\tObject ID: {object_id}\n'
67+
'\tGeneration: {generation}\n').format(
68+
event_type=event_type,
69+
bucket_id=bucket_id,
70+
object_id=object_id,
71+
generation=generation)
72+
73+
payload_format = attributes['payloadFormat']
74+
if payload_format == 'JSON_API_V1':
75+
object_metadata = json.loads(data)
76+
size = object_metadata['size']
77+
content_type = object_metadata['contentType']
78+
metageneration = object_metadata['metageneration']
79+
description += (
80+
'\tContent type: {content_type}\n'
81+
'\tSize: {object_size}\n'
82+
'\tMetageneration: {metageneration}\n').format(
83+
content_type=content_type,
84+
object_size=size,
85+
metageneration=metageneration)
86+
return description
87+
# [END parse_message]
88+
89+
90+
def poll_notifications(subscription_id):
91+
"""Polls a Cloud Pub/Sub subscription for new GCS events for display."""
92+
# [BEGIN poll_notifications]
93+
client = pubsub.Client()
94+
subscription = pubsub.subscription.Subscription(
95+
subscription_id, client=client)
96+
97+
if not subscription.exists():
98+
sys.stderr.write('Cannot find subscription {0}\n'.format(sys.argv[1]))
99+
return
100+
101+
print('Polling for messages. Press ctrl+c to exit.')
102+
while True:
103+
pulled = subscription.pull(max_messages=100)
104+
for ack_id, message in pulled:
105+
print('Received message {0}:\n{1}'.format(
106+
message.message_id, summarize(message)))
107+
subscription.acknowledge([ack_id])
108+
# [END poll_notifications]
109+
110+
111+
if __name__ == '__main__':
112+
parser = argparse.ArgumentParser(
113+
description=__doc__)
114+
parser.add_argument('subscription',
115+
help='The ID of the Pub/Sub subscription')
116+
args = parser.parse_args()
117+
poll_notifications(args.subscription)
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Copyright 2017 Google Inc. All rights reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
from google.cloud.pubsub.message import Message
17+
18+
from notification_polling import summarize
19+
20+
21+
MESSAGE_ID = 12345
22+
23+
24+
def test_parse_json_message():
25+
attributes = {
26+
'eventType': 'OBJECT_FINALIZE',
27+
'bucketId': 'mybucket',
28+
'objectId': 'myobject',
29+
'objectGeneration': 1234567,
30+
'resource': 'projects/_/buckets/mybucket/objects/myobject#1234567',
31+
'notificationConfig': ('projects/_/buckets/mybucket/'
32+
'notificationConfigs/5'),
33+
'payloadFormat': 'JSON_API_V1'}
34+
data = ('{'
35+
' "size": 12345,'
36+
' "contentType": "text/html",'
37+
' "metageneration": 1'
38+
'}')
39+
message = Message(data, MESSAGE_ID, attributes=attributes)
40+
assert summarize(message) == (
41+
'\tEvent type: OBJECT_FINALIZE\n'
42+
'\tBucket ID: mybucket\n'
43+
'\tObject ID: myobject\n'
44+
'\tGeneration: 1234567\n'
45+
'\tContent type: text/html\n'
46+
'\tSize: 12345\n'
47+
'\tMetageneration: 1\n')

storage/cloud-client/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
google-cloud-storage==0.22.0
2+
google-cloud-pubsub==0.22.0

0 commit comments

Comments
 (0)
0