LoginSignup
1
1

More than 3 years have passed since last update.

Cloud Functions APIを使ったPythonからのデプロイ

Last updated at Posted at 2019-06-10

はじめに

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)
1
1
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
1
1