sales_tool/functions/trigger-minutes-workflow-from-miitel/source/main.py
2025-11-17 14:21:29 +09:00

75 lines
2.4 KiB
Python
Executable file

import functions_framework
from google.cloud import storage
from google.cloud.workflows import executions_v1
from google.cloud.workflows.executions_v1.types import Execution
import json
import os
import gzip
# Storage クライアントを作成
cs_client = storage.Client()
wf_client = executions_v1.ExecutionsClient()
@functions_framework.http
def handle_request(request):
# POSTリクエストの処理
if request.method != 'POST':
# 他のメソッドに対するエラーレスポンス
return ({'error': 'Method not allowed'}, 405)
try:
request_json = request.get_json()
print(request_json)
if "challenge" in request_json:
# MiiTelのチャレンジリクエストに対する応答
return (request_json["challenge"], 200, {'Content-Type':'text/plain'})
project_id = os.getenv("PROJECT_ID")
bucket_name = os.getenv("BUCKET") # 共有ドライブID
location = os.getenv("LOCATION") # ワークフローのロケーション
workflow = os.getenv("WORKFLOW") # ワークフロー名
# デバッグ用に保存
save_to_gcs(bucket_name,request_json)
# ワークフロー呼び出し
argument = json.dumps({"video": request_json["video"]})
execution = Execution(argument=argument)
parent = f"projects/{project_id}/locations/{location}/workflows/{workflow}"
print(parent)
response = wf_client.create_execution(request={"parent": parent, "execution": execution})
print(f"Workflow execution started: {response.name}")
return (json.dumps({}), 200, {'Content-Type': 'application/json'})
except Exception as e:
# エラー
error_response = {
"error": str(e) #エラー内容
}
print(str(e))
return json.dumps(error_response), 500, {'Content-Type': 'application/json'} #エラー
def save_to_gcs(bucket_name,request_json):
file_name = request_json["video"]["id"] + ".json.gz"
bucket = cs_client.bucket(bucket_name)
# GCS バケットのブロブを取得
blob = bucket.blob(f"request_log/{file_name}")
# JSONを文字列に変換
json_string = json.dumps(request_json)
# Gzip圧縮
compressed_data = gzip.compress(json_string.encode('utf-8'))
# 圧縮されたデータをアップロード
blob.upload_from_string(compressed_data, content_type='application/gzip')