LoginSignup
7
4

More than 5 years have passed since last update.

Cloud FunctionsのPython Runtimeを使ってPOSTされたJSONをそのまま返すだけの関数を実装する

Last updated at Posted at 2019-02-11

公式ドキュメント

例によって英語じゃないと情報が古い (Pythonランタイムについて書かれていない) のでリンクは英語です。

プロジェクトを作成して、Google Cloud SDKの認証を済ますところまでは、よくある話なので省略します。

手順

適当にプロジェクトを作る (ここでは gcf_parrot とした)。1

mkdir gcf_parrot
cd gcf_parrot
touch main.py

main.pyをいい感じに編集する。
ちなみに type(request)werkzeug.local.LocalProxy です。
返り値は (json文字列, レスポンスコード, ヘッダー) です。

main.py
import json


def generate_exp_design(request):
    param_dict = request.get_json()
    return (json.dumps(param_dict), 200, {})

公式ドキュメントを参考にCORS設定したものはこちら。2

main.py
import json


def generate_exp_design(request):
    # preflight request時
    if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600',
        }
        return ('', 204, headers)

    # main request時
    param_dict = request.get_json()
    headers = {
        'Access-Control-Allow-Origin': '*',
    }
    return (json.dumps(param_dict), 200, headers)

アップロードする。1行目のupdateとinstallは初回のみでOK。

gcloud components update && gcloud components install beta
cd path/to/gcf_parrot
gcloud functions deploy parrot --runtime python37 --trigger-http

できたと思ったら叩いてみる。

curl -H 'Content-Type: application/json' -d '{"foo":"bar","x":[1,2,3]}' https://~~~

{"foo": "bar", "x": [1, 2, 3]} が返ってきたら成功。

余談

axiosで呼ぶ

これがやりたかったんだ…。

axios.post('https://~~~', {
  foo: "bar",
  x: [1, 2, 3],
}, {
  'Content-Type': 'application/json'
}).then(
  (res) => {
    console.log(res.data);
  }
);

その他

  • Flaskが全部いい感じにやってくれるとの噂もあるが試してない
  • gcf_parrot ディレクトリにrequirements.txtを置けば色々ライブラリも用意してくれる
  • curlを叩かなくてもGCPのコンソールからもテストできる

  1. Google Cloud Functionsでオウム返しする関数なので gcf_parrot というだけでとくに意味はない。 

  2. 別ドメインからAPIを叩こうとすると No 'Access-Control-Allow-Origin' header is present on the requested resource. と怒られる。この場合はCORSを有効にしておく必要がある。 

7
4
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
7
4