首页 > 解决方案 > 在本地测试 Python Google Cloud Functions

问题描述

我正在 Google Cloud Functions 上试用 Python3.7 运行时。我能够部署这些功能并在部署后使它们工作,但是,我似乎无法在部署之前运行模拟器在本地测试它们。

谷歌的文档有点不一致,他们告诉你在这里安装谷歌函数模拟器:https ://cloud.google.com/functions/docs/emulator

但是在 Firebase 上,他们会告诉你npm installfirebase-admin、firebase-tools 和 firebase-functions。

所有的模拟器文档都引用了用 JS 编写的示例,没有使用 Python,所以我想知道这些模拟器是否甚至在本地运行 Python 函数?

谢谢

标签: python-3.xfirebasegoogle-cloud-platformgoogle-cloud-functions

解决方案


您可以使用Python 的 Functions Framework在本地运行该函数。

给定一个文件中的函数,main.py如下所示:

def my_function(request):
    return 'Hello World'

你可以做:

$ pip install functions-framework
$ functions-framework --target my_function

这将在http://localhost:8080启动本地开发服务器。

要为 HTTP 函数在本地调用它:

$ curl http://localhost:8080

对于具有非二进制数据的后台函数:

$ curl -d '{"data": {"hi": "there"}}' -X POST \
-H "Content-Type: application/json" \
http://localhost:8080

对于具有二进制数据的背景函数:

$ 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

推荐阅读