Skip to content

Commit f916eb8

Browse files
authored
Merge pull request #477 from GoogleCloudPlatform/pubsub-samples
2 parents 06b5e91 + 2d35546 commit f916eb8

10 files changed

+416
-10
lines changed

.coveragerc

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
11
[run]
22
include =
33
appengine/*
4-
bigtable/*
54
bigquery/*
5+
bigtable/*
66
blog/*
7-
logging/*
87
compute/*
9-
dns/*
108
datastore/*
9+
dataproc/*
10+
dns/*
1111
error_reporting/*
1212
language/*
13-
managed_vms/*
13+
logging/*
1414
monitoring/*
15+
pubsub/*
1516
speech/*
1617
storage/*
18+
vision/*
1719
[report]
1820
exclude_lines =
1921
pragma: NO COVER

nox.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,10 @@ def session_reqcheck(session):
280280
else:
281281
command = 'check-requirements'
282282

283-
for reqfile in list_files('.', 'requirements*.txt'):
283+
reqfiles = list(list_files('.', 'requirements*.txt'))
284+
reqfiles.append('requirements-dev.in')
285+
286+
for reqfile in reqfiles:
284287
session.run('gcprepotools', command, reqfile)
285288

286289

pubsub/cloud-client/README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Google Cloud Pub/Sub Samples
2+
3+
<!-- auto-doc-link -->
4+
<!-- end-auto-doc-link -->
5+
6+
## Prerequisites
7+
8+
All samples require a [Google Cloud Project](https://console.cloud.google.com).
9+
10+
Use the [Cloud SDK](https://cloud.google.com/sdk) to provide authentication:
11+
12+
gcloud beta auth application-default login
13+
14+
Run the samples:
15+
16+
python publisher.py -h
17+
python subscriber.py -h

pubsub/cloud-client/publisher.py

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2016 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 perform basic operations on topics
18+
with the Cloud Pub/Sub API.
19+
20+
For more information, see the README.md under /pubsub and the documentation
21+
at https://cloud.google.com/pubsub/docs.
22+
"""
23+
24+
import argparse
25+
26+
from gcloud import pubsub
27+
28+
29+
def list_topics():
30+
"""Lists all Pub/Sub topics in the current project."""
31+
pubsub_client = pubsub.Client()
32+
33+
topics = []
34+
next_page_token = None
35+
while True:
36+
page, next_page_token = pubsub_client.list_topics()
37+
topics.extend(page)
38+
if not next_page_token:
39+
break
40+
41+
for topic in topics:
42+
print(topic.name)
43+
44+
45+
def create_topic(topic_name):
46+
"""Create a new Pub/Sub topic."""
47+
pubsub_client = pubsub.Client()
48+
topic = pubsub_client.topic(topic_name)
49+
50+
topic.create()
51+
52+
print('Topic {} created.'.format(topic.name))
53+
54+
55+
def delete_topic(topic_name):
56+
"""Deletes an existing Pub/Sub topic."""
57+
pubsub_client = pubsub.Client()
58+
topic = pubsub_client.topic(topic_name)
59+
60+
topic.delete()
61+
62+
print('Topic {} deleted.'.format(topic.name))
63+
64+
65+
def publish_message(topic_name, data):
66+
"""Publishes a message to a Pub/Sub topic with the given data."""
67+
pubsub_client = pubsub.Client()
68+
topic = pubsub_client.topic(topic_name)
69+
70+
# Data must be a bytestring
71+
data = data.encode('utf-8')
72+
73+
message_id = topic.publish(data)
74+
75+
print('Message {} published.'.format(message_id))
76+
77+
78+
if __name__ == '__main__':
79+
parser = argparse.ArgumentParser(
80+
description=__doc__,
81+
formatter_class=argparse.RawDescriptionHelpFormatter
82+
)
83+
84+
subparsers = parser.add_subparsers(dest='command')
85+
subparsers.add_parser('list', help=list_topics.__doc__)
86+
87+
create_parser = subparsers.add_parser('create', help=create_topic.__doc__)
88+
create_parser.add_argument('topic_name')
89+
90+
delete_parser = subparsers.add_parser('delete', help=delete_topic.__doc__)
91+
delete_parser.add_argument('topic_name')
92+
93+
publish_parser = subparsers.add_parser(
94+
'publish', help=publish_message.__doc__)
95+
publish_parser.add_argument('topic_name')
96+
publish_parser.add_argument('data')
97+
98+
args = parser.parse_args()
99+
100+
if args.command == 'list':
101+
list_topics()
102+
elif args.command == 'create':
103+
create_topic(args.topic_name)
104+
elif args.command == 'delete':
105+
delete_topic(args.topic_name)
106+
elif args.command == 'publish':
107+
publish_message(args.topic_name, args.data)

pubsub/cloud-client/publisher_test.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Copyright 2016 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+
from gcloud import pubsub
16+
from gcp.testing import eventually_consistent
17+
import pytest
18+
19+
import publisher
20+
21+
TEST_TOPIC = 'publisher-test-topic'
22+
23+
24+
@pytest.fixture
25+
def test_topic():
26+
client = pubsub.Client()
27+
topic = client.topic(TEST_TOPIC)
28+
yield topic
29+
if topic.exists():
30+
topic.delete()
31+
32+
33+
def test_list(test_topic, capsys):
34+
test_topic.create()
35+
36+
@eventually_consistent.call
37+
def _():
38+
publisher.list_topics()
39+
out, _ = capsys.readouterr()
40+
assert test_topic.name in out
41+
42+
43+
def test_create(test_topic):
44+
publisher.create_topic(test_topic.name)
45+
46+
@eventually_consistent.call
47+
def _():
48+
assert test_topic.exists()
49+
50+
51+
def test_delete(test_topic):
52+
test_topic.create()
53+
54+
publisher.delete_topic(test_topic.name)
55+
56+
@eventually_consistent.call
57+
def _():
58+
assert not test_topic.exists()
59+
60+
61+
def test_publish(test_topic, capsys):
62+
test_topic.create()
63+
64+
publisher.publish_message(test_topic.name, 'hello')
65+
66+
out, _ = capsys.readouterr()
67+
assert 'published' in out

pubsub/cloud-client/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
gcloud==0.18.1

pubsub/cloud-client/subscriber.py

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2016 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 perform basic operations on
18+
subscriptions with the Cloud Pub/Sub API.
19+
20+
For more information, see the README.md under /pubsub and the documentation
21+
at https://cloud.google.com/pubsub/docs.
22+
"""
23+
24+
import argparse
25+
26+
from gcloud import pubsub
27+
28+
29+
def list_subscriptions(topic_name):
30+
"""Lists all subscriptions for a given topic."""
31+
pubsub_client = pubsub.Client()
32+
topic = pubsub_client.topic(topic_name)
33+
34+
subscriptions = []
35+
next_page_token = None
36+
while True:
37+
page, next_page_token = topic.list_subscriptions()
38+
subscriptions.extend(page)
39+
if not next_page_token:
40+
break
41+
42+
for subscription in subscriptions:
43+
print(subscription.name)
44+
45+
46+
def create_subscription(topic_name, subscription_name):
47+
"""Create a new pull subscription on the given topic."""
48+
pubsub_client = pubsub.Client()
49+
topic = pubsub_client.topic(topic_name)
50+
51+
subscription = topic.subscription(subscription_name)
52+
subscription.create()
53+
54+
print('Subscription {} created on topic {}.'.format(
55+
subscription.name, topic.name))
56+
57+
58+
def delete_subscription(topic_name, subscription_name):
59+
"""Deletes an existing Pub/Sub topic."""
60+
pubsub_client = pubsub.Client()
61+
topic = pubsub_client.topic(topic_name)
62+
subscription = topic.subscription(subscription_name)
63+
64+
subscription.delete()
65+
66+
print('Subscription {} deleted on topic {}.'.format(
67+
subscription.name, topic.name))
68+
69+
70+
def receive_message(topic_name, subscription_name):
71+
"""Receives a message from a pull subscription."""
72+
pubsub_client = pubsub.Client()
73+
topic = pubsub_client.topic(topic_name)
74+
subscription = topic.subscription(subscription_name)
75+
76+
# Change return_immediately=False to block until messages are
77+
# received.
78+
results = subscription.pull(return_immediately=True)
79+
80+
print('Received {} messages.'.format(len(results)))
81+
82+
for ack_id, message in results:
83+
print('* {}: {}, {}'.format(
84+
message.message_id, message.data, message.attributes))
85+
86+
# Acknowledge received messages. If you do not acknowledge, Pub/Sub will
87+
# redeliver the message.
88+
if results:
89+
subscription.acknowledge([ack_id for ack_id, message in results])
90+
91+
92+
if __name__ == '__main__':
93+
parser = argparse.ArgumentParser(
94+
description=__doc__,
95+
formatter_class=argparse.RawDescriptionHelpFormatter
96+
)
97+
98+
subparsers = parser.add_subparsers(dest='command')
99+
list_parser = subparsers.add_parser(
100+
'list', help=list_subscriptions.__doc__)
101+
list_parser.add_argument('topic_name')
102+
103+
create_parser = subparsers.add_parser(
104+
'create', help=create_subscription.__doc__)
105+
create_parser.add_argument('topic_name')
106+
create_parser.add_argument('subscription_name')
107+
108+
delete_parser = subparsers.add_parser(
109+
'delete', help=delete_subscription.__doc__)
110+
delete_parser.add_argument('topic_name')
111+
delete_parser.add_argument('subscription_name')
112+
113+
receive_parser = subparsers.add_parser(
114+
'receive', help=receive_message.__doc__)
115+
receive_parser.add_argument('topic_name')
116+
receive_parser.add_argument('subscription_name')
117+
118+
args = parser.parse_args()
119+
120+
if args.command == 'list':
121+
list_subscriptions(args.topic_name)
122+
elif args.command == 'create':
123+
create_subscription(args.topic_name, args.subscription_name)
124+
elif args.command == 'delete':
125+
delete_subscription(args.topic_name, args.subscription_name)
126+
elif args.command == 'receive':
127+
receive_message(args.topic_name, args.subscription_name)

0 commit comments

Comments
 (0)