首页 > 解决方案 > 如何将 Google Cloud Firestore 本地模拟器用于 python 和测试目的

问题描述

我试图找出如何将firestore本地模拟器用于python和用于测试目的。但我找不到操作方法文档。

有人可以帮我吗?

标签: pythongoogle-cloud-platformgoogle-cloud-firestore

解决方案


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

initialize_app这将涉及使用上下文调用,credentials然后创建一个传统的 Firestore 客户端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()

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

npx firebase setup:emulators:firestore
npx firebase --token $FIREBASE_TOKEN emulators:start --only firestore --project $PROJECT_KEY

最后,在已经实例化的实例中注入重定向,以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)

现在,您的db对象将毫无问题地与本地模拟器进行交互。

感谢John Cartergcloud 内部 api 上解决这个问题


推荐阅读