0
0

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 1 year has passed since last update.

Python3: Google Cloud Functions で加算

Last updated at Posted at 2022-04-06

フォルダー構造

$ tree
.
├── main.py
└── requirements.txt
main.py
def sum_up(request):
	request_json = request.get_json()
	aa = 0
	bb = 0
#	
	if 'aa' in request_json:
		aa = int(request_json['aa'])

	if 'aa' in request_json:
		bb = int(request_json['bb'])
#
	sum = aa + bb
	rvalue = {}
	rvalue['sum'] = sum
	rvalue['aa'] = aa
	rvalue['bb'] = bb

	return rvalue
requirements.txt
# Function dependencies, for example:
# package>=version

ローカルでテスト

サーバーの起動

functions-framework --target=sum_up

curl でテスト

curl_post_local.sh
curl -X POST $HOST \
 -H "Content-Type: application/json" \
 -d '{"aa": 32, "bb": 58}'
echo ""

Httpie でテスト

http_post_local.sh
HOST="http://localhost:8080"
http $HOST \
  aa=12 bb=45

Cloud Functions でテスト

デプロイ

gcloud functions deploy function-apr06 \
--entry-point=sum_up \
--trigger-http \
--runtime=python39 \
--region asia-northeast1

curl でテスト

curl_post_cloud.sh
HOST="https://asia-northeast1-project-apr06.cloudfunctions.net"
curl -X POST $HOST/function-apr06 \
 -H "Content-Type: application/json" \
 -H "Authorization: bearer $(gcloud auth print-identity-token)" \
 -d '{"aa": 123, "bb": 546}'

Httpie でテスト

http_post_cloud.sh
HOST="https://asia-northeast1-project-apr06.cloudfunctions.net"
http $HOST/function-apr06 \
  "Authorization: bearer $(gcloud auth print-identity-token)" \
  aa=23 bb=56

Python でテスト

トークンの取得

get_token.sh
gcloud auth print-identity-token > access_token.txt
client.py
#! /usr/bin/python3
#
#	client.py
#
#					Apr/23/2022
#
# ------------------------------------------------------------------
import  sys
import  requests
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
with open('access_token.txt') as ff:
	access_token = ff.read().strip()
#
host="https://asia-northeast1-project-apr06.cloudfunctions.net"
url_aa=host + "/function-apr06"
#
headers = {'Authorization': 'bearer {}'.format(access_token)}
#
payload = {}
payload["aa"] = 16
payload["bb"] = 48
#
rr = requests.post(url_aa,json=payload,headers=headers)
#
print(rr.text)
print(rr)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?