Test Python Google Cloud Functions Locally
Solution 1:
You can use the Functions Framework for Python to run the function locally.
Given a function in a file named main.py
like so:
defmy_function(request):
return'Hello World'
You can do:
$ pip install functions-framework
$ functions-framework --target my_function
Which will start a local development server at http://localhost:8080.
To invoke it locally for an HTTP function:
$ curl http://localhost:8080
For a background function with non-binary data:
$ curl -d '{"data": {"hi": "there"}}' -X POST \
-H "Content-Type: application/json" \
http://localhost:8080
For a background function with binary data:
$ curl -d "@binary_file.file" -X POST \
-H "Ce-Type: true" \
-H "Ce-Specversion: true" \
-H "Ce-Source: true" \
-H "Ce-Id: true" \
-H "Content-Type: application/json" \
http://localhost:8080
Solution 2:
Update
Please, use the official emulator and serving framework from GCP https://github.com/GoogleCloudPlatform/functions-framework-python
You can install it with
pip install functions-framework
Deprecated
Based on Dustin's answer I've developed a package to serve as emulator:
pip install gcp-functions-emulator
Given you want to serve the following function
# mycloudfunction.pydefapi(request):
return'important data'
To emulate we have to call it like so:
gcpfemu <path/to/file.py> <function_name>
For example, with the code above we will call it:
gcpfemu mycloudfunction.py api
And to access the data we can use for example curl:
curl localhost:5000/api
> important data
Solution 3:
To run it in IntelliJ with Target Type = Script Path
and the default options it should look like this:
from flask import Flask, request
app = Flask(__name__)
@app.route('/')defhello():
return hello_get(request)
if __name__ == '__main__':
app.run('127.0.0.1', debug=True)
Solution 4:
See this project on GitHub: GoogleCloudPlatform/functions-framework
Currently there are only implementations in Node.js, Go, and PHP, but see Issue #5 about the Python implementation.
I suggest, whatever implementation you use, to follow the Functions Framework Contract
UPDATE: As Dustin mentioned, there is also a Python implementation now.
Post a Comment for "Test Python Google Cloud Functions Locally"