1
+ import os , json
2
+ from google .cloud import pubsub_v1
3
+ from google .auth import jwt
4
+
5
+
6
+ os .environ ['GOOGLE_APPLICATION_CREDENTIALS' ] = os .getcwd () + "/PubSubService.json" #import pubsub serveice credential json file
7
+
8
+ # The same for the publisher, except that the "audience" claim needs to be adjusted
9
+ # publisher_audience = "https://pubsub.googleapis.com/google.pubsub.v1.Publisher"
10
+ subscriber = pubsub_v1 .SubscriberClient ()
11
+ publisher = pubsub_v1 .PublisherClient ()
12
+
13
+
14
+ def publish_messages (project_id , topic_name ):
15
+ """Publishes multiple messages to a Pub/Sub topic."""
16
+ # [START pubsub_quickstart_publisher]
17
+ # [START pubsub_publish]
18
+ project_id = "Your Project Id"
19
+ topic_name = "Your Topic Name"
20
+
21
+ publisher = pubsub_v1 .PublisherClient ()
22
+ # The `topic_path` method creates a fully qualified identifier
23
+ # in the form `projects/{project_id}/topics/{topic_name}`
24
+ topic_path = publisher .topic_path (project_id , topic_name )
25
+
26
+ for n in range (1 , 10 ):
27
+ data = u'Message number {}' .format (n )
28
+ # Data must be a bytestring
29
+ data = data .encode ('utf-8' )
30
+ # When you publish a message, the client returns a future.
31
+ future = publisher .publish (topic_path , data = data )
32
+ print (future .result ())
33
+
34
+ print ('Published messages.' )
35
+
36
+ publish_messages ("project_id" ,"topic_name" )
0 commit comments