How to use Google Cloud Firestore local emulator for python and for testing purpose

孤街浪徒 提交于 2021-02-18 22:43:56

问题


I tried to find out how to use firestore local emulator for python and for testing purpose. But I can not find out how-to document.

Could somebody help me?


回答1:


Welcome to SO :)

The primary purpose of the Cloud Firestore Emulator (at the moment) seems to be to test security rules, as documented here. This section states: "The only SDK that currently supports the emulator is the Node.js SDK."

Confusingly there are also these Ruby docs for the Google Cloud Client Libraries. The same thing does not seem to be available in Python yet.

Here are instructions for running the emulator as part of the Google Cloud SDK.


Consider using Cloud Firestore in Datastore mode, which has better tooling (it's probably just had more time to mature). You can find instructions for running its emulator on the Running the Datastore mode Emulator page.

Use the Choosing between Native Mode and Datastore Mode page to decide which direction you want to take. If you feel you need the additional 'Native mode' features, it'll probably be easiest to connect straight to a real Firestore instance in the cloud.




回答2:


Using the firebase_admin python module, follow the standard setup documented in the Cloud Firestore Docs

This will involve calling initialize_app with a credentials context and then creating a traditional Firestore Client with firestore.client()

For example:

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()

Next, you will need to install and run the Firestore Emulator, which will host the a local Firestore instance over localhost:8080.

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

Finally, inject a redirect in the already instantiated firestore.client instance to interact with the local emulator host/port using an insecure GRPC channel:

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)

Now, your db object will interact with the local emulator without any problems.

Acknowledgements to John Carter for figuring this out on the gcloud internal api



来源:https://stackoverflow.com/questions/54868011/how-to-use-google-cloud-firestore-local-emulator-for-python-and-for-testing-purp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!