run a single function
export GCLOUD_PROJECT="XXX"
export GOOGLE_ACCOUNT="your@email.com"
echo "GOOGLE_ACCOUNT=$GOOGLE_ACCOUNT"
export GOOGLE_APPLICATION_CREDENTIALS=$HOME/.config/gcloud/legacy_credentials/${GOOGLE_ACCOUNT}/adc.json
export YOUR_ENV_VAR="foo"
pip3 install functions-framework
functions-framework --source ./path/to/yuor/main.py --target your_python_function_name --debug
run a custom api functions/run_functions_locally.py
from flask import Flask, request
from my_function_a.main import my_python_function_a
from my_function_b.main import my_python_function_b
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.get('/api/a')
def get_a():
return my_python_function_a(request)
@app.post('/api/b')
def post_b():
return my_python_function_b(request)
functions/my_python_function_a/main.py
import functions_framework
YOUR_ENV_VAR = os.getenv("YOUR_ENV_VAR")
@functions_framework.http
def my_python_function_b(request):
headers = {
'Access-Control-Allow-Origin': '*',
}
return "hello from function a YOUR_ENV_VAR=" + YOUR_ENV_VAR, 200, headers
functions/my_python_function_b/main.py
import functions_framework
YOUR_ENV_VAR = os.getenv("YOUR_ENV_VAR")
@functions_framework.http
def my_python_function_b(request):
headers = {
'Access-Control-Allow-Origin': '*',
}
return "hello from function a YOUR_ENV_VAR=" + YOUR_ENV_VAR, 200, headers
run
export GCLOUD_PROJECT="XXX"
export GOOGLE_ACCOUNT="your@email.com"
echo "GOOGLE_ACCOUNT=$GOOGLE_ACCOUNT"
export GOOGLE_APPLICATION_CREDENTIALS=$HOME/.config/gcloud/legacy_credentials/${GOOGLE_ACCOUNT}/adc.json
export YOUR_ENV_VAR="foo"
pip3 install flask
flask --app ./api-stack/functions/run_functions_locally run
curl
curl -X GET http://127.0.0.1:5000/api/a
curl -X POST -H "Content-Type: application/json" --data '{"foo":"bar"}' http://127.0.0.1:5000/api/b
inspiration:
- GoogleCloudPlatform/functions-framework-python: FaaS (Function as a service) framework for writing portable Python functions
- Running multiple Google Cloud functions locally with the functions-framework - DEV Community
- Quickstart — Flask Documentation (2.2.x)
- python - Get the data received in a Flask request - Stack Overflow
- How do I import other Python files? - Stack Overflow