@@ -47,18 +47,67 @@ to Cloud Pub/Sub using this Client Library.
4747
4848.. _Pub/Sub documentation : http://google-cloud-python.readthedocs.io/en/latest/pubsub/index.html
4949
50- To get started with this API, you'll need to create
5150
52- .. code :: python
51+ Publishing
52+ ----------
5353
54+ To publish data to Cloud Pub/Sub you must create a topic, and then publish
55+ messages to it
56+
57+ .. code-block :: python
58+
59+ import os
5460 from google.cloud import pubsub
5561
56- client = pubsub.Client()
57- topic = client.topic(' topic_name' )
58- topic.create()
62+ publisher = pubsub.PublisherClient()
63+ topic = ' projects/{project_id} /topics/{topic} ' .format(
64+ project_id = os.getenv(' GOOGLE_CLOUD_PROJECT' ),
65+ topic = ' MY_TOPIC_NAME' , # Set this to something appropriate.
66+ )
67+ publisher.create_topic()
68+ publisher.publish(topic, b ' My first message!' , spam = ' eggs' )
69+
70+ To learn more, consult the :doc: `publishing documentation `_.
71+
72+ .. _publishing documentation: http://google-cloud-python.readthedocs.io/en/latest/pubsub/publisher/index.html
73+
74+
75+ Subscribing
76+ -----------
77+
78+ To subscribe to data in Cloud Pub/Sub, you create a subscription based on
79+ the topic, and subscribe to that.
80+
81+ .. code-block:: python
82+
83+ import os
84+ from google.cloud import pubsub
85+
86+ subscriber = pubsub.SubscriberClient()
87+ topic = 'projects/{project_id}/topics/{topic}'.format(
88+ project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
89+ topic='MY_TOPIC_NAME', # Set this to something appropriate.
90+ )
91+ subscription_name = 'projects/{project_id}/subscriptions/{sub}'.format(
92+ project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
93+ sub='MY_SUBSCRIPTION_NAME', # Set this to something appropriate.
94+ )
95+ subscription = subscriber.create_subscription(topic, subscription)
96+
97+ The subscription is opened asychronously, and messages are processed by
98+ use of a callback.
99+
100+ .. code-block:: python
101+
102+ def callback(message):
103+ print(message.data)
104+ message.ack()
105+ subscription.open(callback)
106+
107+ To learn more, consult the :doc:`subscriber documentation`_.
108+
109+ .. _subscriber documentation: http://google-cloud-python.readthedocs.io/en/latest/pubsub/subscriber/index.html
59110
60- topic.publish(' this is the message_payload' ,
61- attr1 = ' value1' , attr2 = ' value2' )
62111
63112.. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-pubsub.svg
64113 :target: https://pypi.org/project/google-cloud-pubsub/
0 commit comments