如何将Google Cloud Firestore本地模拟器用于python和进行测试

Wis*_*dog 5 python google-cloud-platform google-cloud-firestore

我试图找出如何将Firestore本地仿真器用于python和进行测试。但是我找不到操作文档。

有人可以帮我吗?

Fan*_*Bao 10

截至目前,firebase_admin只需设置这两个环境变量,就可以将任何 SDK 连接到 firebase 模拟器。我亲自在 Python SDK 上对此进行了测试,它非常有效。

export FIRESTORE_EMULATOR_HOST="localhost:8080"
export GCLOUD_PROJECT="any-valid-name"
Run Code Online (Sandbox Code Playgroud)

文档链接


bsz*_*zom 5

欢迎来到SO:)

Cloud Firestore 模拟器(目前)的主要目的似乎是测试安全规则,如此处所述本节指出:“当前支持模拟器的唯一 SDK 是 Node.js SDK。”

令人困惑的是,还有这些针对 Google Cloud 客户端库的 Ruby 文档。Python 中似乎还没有提供同样的功能。

以下是有关将模拟器作为 Google Cloud SDK 的一部分运行的说明。


考虑在 Datastore 模式下使用Cloud Firestore ,它具有更好的工具(可能只是有更多的时间来成熟)。您可以在运行数据存储模式模拟器页面上找到运行模拟器的说明。

使用“在本机模式和数据存储模式之间进行选择”页面来决定要采取的方向。如果您觉得需要额外的“本机模式”功能,直接连接到云中的真实 Firestore 实例可能是最简单的方法。


dee*_*ent 5

使用firebase_adminpython模块,遵循Cloud Firestore文档中记录的标准设置

这将涉及initialize_app使用credentials上下文进行调用,然后使用以下命令创建传统的Firestore Client:firestore.client()

例如:

from firebase_admin import credentials, firestore, initialize_app

firebase_credentials_file_path = ...
cred = credentials.Certificate(firebase_credentials_file_path)
initialize_app(cred)
db = firestore.client()
Run Code Online (Sandbox Code Playgroud)

接下来,您将需要安装并运行Firestore Emulator,它将在上托管本地Firestore实例localhost:8080

npx firebase setup:emulators:firestore
npx firebase --token $FIREBASE_TOKEN emulators:start --only firestore --project $PROJECT_KEY
Run Code Online (Sandbox Code Playgroud)

最后,在已实例化的firestore.client实例中注入重定向,以使用不安全的GRPC通道与本地仿真器主机/端口进行交互:

import grpc
from google.cloud.firestore_v1.gapic import firestore_client
from google.cloud.firestore_v1.gapic.transports import firestore_grpc_transport

channel = grpc.insecure_channel("localhost:8080")
transport = firestore_grpc_transport.FirestoreGrpcTransport(channel=channel)
db._firestore_api_internal = firestore_client.FirestoreClient(transport=transport)
Run Code Online (Sandbox Code Playgroud)

现在,您的db对象将与本地仿真器进行交互,而不会出现任何问题。

致谢对约翰·卡特在gcloud内部API搞清楚了这一点