9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Cloud Functions Pythonを使ったローカル開発環境とデプロイ方法

Posted at

Cloud Functions Pythonを使ったローカル開発環境とデプロイ方法

はじめに

最初に毎回、Functionsにデプロイして実行するのは手間なのでローカル実行できるようにする
function-frameworkをインストールしローカル実行する
その後、Cloud Functionsにデプロイする

$ pip install functions-framework

HTTPサンプル作成

main.py 作成

def sample_http(request):
    return "sample"

main.py ディレクトリに移動
下記functions-frameworkコマンド実行で localhost:8080 がFunctionsの呼び出し元になる

$ functions-framework --target sample_http --signature-type=http --port=8080 --debug
 * Serving Flask app "sample" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
 * Restarting with fsevents reloader
 * Debugger is active!
 * Debugger PIN: 120-504-718

デプロイ

$ gcloud functions deploy sample_http \
--runtime python37 --trigger-http --allow-unauthenticated

確認

$ curl "https://REGION-PROJECT_ID.cloudfunctions.net/sample" 

PUBSUBサンプル作成

main.py作成

from flask import current_app


def sample_pubsub(event, context):
    current_app.logger.info("sample")

main.py ディレクトリに移動
下記functions-frameworkコマンド実行で localhost:8080 がFunctionsの呼び出し元になる

$ functions-framework --target sample_pubsub --signature-type=event --port=8080 --debug
 * Serving Flask app "sample" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
 * Restarting with fsevents reloader
 * Debugger is active!
 * Debugger PIN: 120-504-718

PUBSUB実行はPOST、Content-typeはapplication/jsonアクセスしないといけない
ログがコンソールに出力される

curl -X POST -H'Content-type: application/json' -d "{\"key\":\"value\"}"  "http://localhost:8080"
[2021-01-23 03:40:15,954] INFO in main: sample

デプロイ

gcloud functions deploy sample_pubsub \ 
--entry-point=sample_pubsub --runtime python37 \
--trigger-topic sample_pubsub --allow-unauthenticated

Cloud Functions コンソールのテストにて確認
screencapture-console-cloud-google-functions-details-us-central1-sample-pubsub-2021-01-23-03_53_31.png

9
3
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
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?