gcloud の Pub/Sub を python3 で行う

参考にしたページ
[Publishing Messages](https://googlecloudplatform.github.io/google-cloud-python/latest/pubsub/publisher/index.html#publish-a-message)
[Subscribing to Messages](https://googlecloudplatform.github.io/google-cloud-python/latest/pubsub/subscriber/index.html#pulling-a-subscription)

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

この JSON　(サービス アカウント キー） は、google console で作成してダウンロードします。
![key_feb0801.png](https://qiita-image-store.s3.amazonaws.com/0/179446/4e62cc02-71f3-6ad8-0978-4efc9628ff51.png)


トピックの作成

```py3: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")
# ------------------------------------------------------------------
```

実行スクリプト

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

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

```py3: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")
# ------------------------------------------------------------------
```

実行スクリプト

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


パブリッシュ

```py3: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")
# ------------------------------------------------------------------
```


実行スクリプト

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

サブスクライブ

```py3: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")
# ------------------------------------------------------------------
```

実行スクリプト

```bash
export GOOGLE_APPLICATION_CREDENTIALS="./my-project-sep-10-2017.json"
./iot_subscribe.py
```