When building a backend on Google Cloud Platform, it takes about a minute to deploy, so it is smooth to build an environment that emulates locally during development. Here's how to emulate Cloud Functions in a Python environment.
Create a function called hello in main.py and put it
main.py
def hello(request):
request_json = request.get_json()
if request.args and 'message' in request.args:
return request.args.get('message')+'get'
elif request_json and 'message' in request_json:
return request_json['message']+'post'
else:
return f'Hello Worlds!'
In that folder, type the terminal below.
terminal.
functions-framework --target=hello
When specifying the port, it is as follows.
terminal.
functions-framework --target=hello --port=8081
A curl command for debugging.
get.communication
curl -X GET "localhost:8081/?message=Hi,get"
post.communication
curl -X POST -H "Content-Type: application/json" -d '{"message":"hi,post"}' localhost:8081/
main.py
def hello(request):
request_json = request.get_json()
headers = {
'Access-Control-Allow-Origin': '*',
}
"""
headers = {
'Access-Control-Allow-Origin': 'https://example.com',
}
"""
if request.args and 'message' in request.args:
return (request.args.get('message')+'get', 200, headers)
elif request_json and 'message' in request_json:
return (request_json['message']+'post', 200, headers)
else:
return (f'Hello Worlds!', 200, headers)
Deployment
If all goes well, deploy to GCP.
terminal.
gcloud functions deploy hello \
--runtime python37 --trigger-http --allow-unauthenticated
https://cloud.google.com/functions/docs/quickstart
https://github.com/GoogleCloudPlatform/functions-framework-python
In reality, the return value is often in JSON format, so that's the case.
main.py
import json
def hello(request):
request_json = request.get_json()
headers = {
'Access-Control-Allow-Origin': 'http://localhost:8080',
}
"""
headers = {
'Access-Control-Allow-Origin': 'https://example.com',
}
"""
print('called')
if request.args and 'message' in request.args:
input = request.args.get('message')
rtrn = {'output':'hi %s(get)'%(input)}
return (json.dumps(rtrn), 200, headers)
elif request_json and 'message' in request_json:
input = request_json['message']
rtrn = {'output':'hi %s(post)'%(input)}
return (json.dumps(rtrn), 200, headers)
else:
rtrn = {'output':'hi (no args)'}
return (json.dumps(rtrn), 200, headers)
For non-standard modules, you need to create requirement.txt, but in this case it's just json so you don't need it.
Recommended Posts