LoginSignup
4
3

More than 3 years have passed since last update.

gcloud の Pub/Sub を python3 で行う

Last updated at Posted at 2018-02-08

参考にしたページ
Publishing Messages
Subscribing to Messages

プログラムを実行するには、
認証の JSON ファイルが必要です。
この 例では、my-project-sep-10-2017.json としました。

この JSON (サービス アカウント キー) は、google console で作成してダウンロードします。
key_feb0801.png

トピックの作成

create_topic.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   create_topic.py
#
#                       Feb/08/2018
# ------------------------------------------------------------------
import  sys 
from google.cloud import pubsub

# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
publisher = pubsub.PublisherClient()

project_id = 'my-project-sep-10-2017'
topic_name = 'topic_1'
topic_path = publisher.topic_path(project_id,topic_name)

try:
    topic = publisher.create_topic(topic_path)
    print('Topic created: {}'.format(topic))
except Exception as ee:
    sys.stderr.write("*** error *** in publisher.create_topic ***\n")
    sys.stderr.write(str(ee) + "\n")

sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行スクリプト

export GOOGLE_APPLICATION_CREDENTIALS="./my-project-sep-10-2017.json"
./create_topic.py

サブスクリプションの作成

create_subscribe.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   create_subscribe.py
#
#                       Feb/08/2018
# ------------------------------------------------------------------
import  sys 
from google.cloud import pubsub
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
subscriber = pubsub.SubscriberClient()

topic_name = 'projects/my-project-sep-10-2017/topics/topic_1'
sub_name = 'projects/my-project-sep-10-2017/subscriptions/subscription_1'

try:
    subscriber.create_subscription(sub_name, topic_name)
except Exception as ee:
    sys.stderr.write("*** error *** in subscriber.create_subscription ***\n")
    sys.stderr.write(str(ee) + "\n")

#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行スクリプト

export GOOGLE_APPLICATION_CREDENTIALS="./my-project-sep-10-2017.json"
./create_subscribe.py

パブリッシュ

iot_publish.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   iot_publish.py
#
#                       Feb/08/2018
# ------------------------------------------------------------------
import  sys 
import  datetime
from google.cloud import pubsub
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
publisher = pubsub.PublisherClient()

project_id = 'my-project-sep-10-2017'
topic_name = 'topic_1'
topic_path = publisher.topic_path(project_id,topic_name)

dd = datetime.datetime.today()
message = 'This is my message. ' + dd.strftime("%Y-%m-%d %H:%M:%S") 
sys.stderr.write(message + "\n")

message_bb = message.encode()

publish_client = pubsub.PublisherClient()
publish_client.publish(topic_path, message_bb)

sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行スクリプト

export GOOGLE_APPLICATION_CREDENTIALS="./my-project-sep-10-2017.json"
./iot_publish.py

サブスクライブ

iot_subscribe.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   iot_subscribe.py
#
#                       Feb/08/2018
# ------------------------------------------------------------------
import  sys 
from google.cloud import pubsub
# ------------------------------------------------------------------
def callback(message):
    print(message)  # Replace this with your actual logic.
    message.ack()
#
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
subscriber = pubsub.SubscriberClient()

sub_name = 'projects/my-project-sep-10-2017/subscriptions/subscription_1'

subscription = subscriber.subscribe(sub_name)

future = subscription.open(callback)

try:
    try:
        future.result()
    except Exception as ex:
        subscription.close()
        sys.stderr.write(str(ex) + "\n")
except KeyboardInterrupt:
    sys.stderr.write('*** interrupted! ***\n')
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行スクリプト

export GOOGLE_APPLICATION_CREDENTIALS="./my-project-sep-10-2017.json"
./iot_subscribe.py
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3