【GCP+Python3】Pub/Subトリガーで起動するCloudFunctionの作り方

自分で作ったサンプルプログラムすぐ見失うから。

やりたいこと

何かでPub/Subが飛んできたらCloudFunctionが動いて、飛んできたデータを加工して別のStorage等に保存する仕組みを作りたい。

結論

import base64
import regist

def main(event, context):
   """Background Cloud Function to be triggered by Pub/Sub.
   Args:
           event (dict):  The dictionary with data specific to this type of
           event. The `data` field contains the PubsubMessage message. The
           `attributes` field will contain custom attributes if there are any.
           context (google.cloud.functions.Context): The Cloud Functions event
           metadata. The `event_id` field contains the Pub/Sub message ID. The
           `timestamp` field contains the publish time.
   """
   print("*********************regist start*********************")

   print(event)

   if 'data' not in event:
       print("Pub/Subメッセージにdataが存在しません")
       return(False)
   
   if 'attributes' not in event:
       print("Pub/Subメッセージにattributesが存在しません")
       return(False)
       
   message = base64.b64decode(event['data']).decode('utf-8')
   
   if message == "start":
       print("START::::::::::::::::::::::::::::")
       r = regist.register(event['attributes'])
       r.regist()
      
      

# regist.py↓↓      
 
class register():
  def __init__(self,receiptDatas):
      # attributesとして受け取ったデータを分解する
      self.receiptDatas = receiptDatas
      self.hoge = receiptDatas["hoge"]
      self.huga = receiptDatas["huga"]
       
  def regist(self):    
       
      print("ここで具体的に登録作業をする")
      return(True)

基本は公式ドキュメント通り。

Pub/Subで送られてきた情報を分解するところすぐ解らなくなるのでメモ。

・Pub/Subメッセージはテキストのmessage部分とJSONのattributeの両方もしくはどちらかで届く。(上記はmessageとattributeが揃ってないと動かない仕様。)
・Pub/Subで発火する関数の引数に(event,context)を指定する。
・messageはeventオブジェクトのmessageに入ってくる。base64でエンコードされているのでデコードして使う。
・attributesはeventオブジェクトのattributesに入ってくる。
・contextsにはメタデータが入ってる。

データを分解するところは、ただ全部のキーをselfに入れるだけならもうちょっとスマートに書けるだろうけど、サンプルはなんかこう日付を年月日に分解したりとかこのキーに値が入ってなかったらデフォルト値入れるとかそういうこまこましたことをやる前提。

デプロイのやり方もすぐ忘れるよねお前

gcloud functions deploy FUNCTION_NAME --trigger-topic TOPIC_NAME --runtime=python37 

rruntimeとtrigger-topicの指定は最初のデプロイの時だけでOK。

この記事が気に入ったらサポートをしてみませんか?