Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 607e443

Browse files
committed
add pubsub snippet for python
1 parent dab5c04 commit 607e443

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
- [Not Found Page](react-js/NotFound.js)
2626

2727
## Python
28+
- [Google Cloud Pub/Sub](python/pubsub.py)
2829
- [Dockerize Flask App](python/Dockerfile)
2930
- [Cython Compile File Generator](python/compile.py)
3031
- [Camera Live Streaming with Flask and Open-CV](python/camera.py)

‎python/pubsub.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /