はじめに
GCPのCloud Functionsに作成したZIPファイルをデプロイする際に、APIを使う方法のメモ。記事っぽく色々書こうと思ったけど時間が無いので一旦流れのみ。そのうち、時間を見つけて親切に書くかもしれない。
サービスアカウントの用意
コンソールからAPIとサービス
を開き、認証情報
を認証情報を作成
で、サービスアカウント キー
を選択。
役割の項目から、Cloud Functions 開発者
とストレージのオブジェクト作成者
の権限をつけたサービスアカウントを作成して、JSONファイルをダウンロードする。
目的の関数をzip化
一旦は以下のような簡単なものを使うことにする。test_function.zip
という名前で保存。
def handler(request):
return 'OK'
Deployしよう
セッションの立ち上げ
credentials = service_account.Credentials.from_service_account_file('service_account.json')
scoped_credentials = credentials.with_scopes(
[
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/cloudfunctions'
])
authed_session = AuthorizedSession(scoped_credentials)
アップロードURLの取得
url_base = 'https://cloudfunctions.googleapis.com/v1/'
url = url_base + 'projects/{project_id}/locations/{location_id}/functions:generateUploadUrl'
response = authed_session.post(url, headers=headers)
ret = json.loads(response.content.decode('utf-8'))
uploadUrl = ret['uploadUrl']
zipのアップロード
with open('test_function.zip', 'rb') as f:
img_byte= io.BytesIO(f.read())
headers ={
'content-type': 'application/zip',
'x-goog-content-length-range': '0,104857600'
}
ret = requests.put(uploadUrl, data=img_byte.getvalue(), headers=headers)
最初のデプロイ
url = url_base + 'projects/{project_id}/locations/{location_id}/functions'
headers ={
'content-type': 'application/json'
}
body = {
"name": "projects/{project_id}/locations/{location_id}/functions/{function_name}",
"description": "test_upload",
"entryPoint": "handler",
"runtime": "python37",
"sourceUploadUrl": uploadUrl,
"httpsTrigger": {}
}
ret = authed_session.post(url, json=body, headers=headers)
デプロイしたモデルを更新する場合
url = url_base + 'projects/{project_id}/locations/{location_id}/functions/{function_name}'
ret = authed_session.patch(url, json=body, headers=headers)