-
-
Save therefromhere/5acc827ec7a27db9edcb24fe2ece7d37 to your computer and use it in GitHub Desktop.
import os | |
from unittest import mock | |
import grpc | |
from google.auth.credentials import Credentials | |
from google.cloud import firestore | |
from google.cloud.firestore_v1.gapic import firestore_client | |
from google.cloud.firestore_v1.gapic.transports import firestore_grpc_transport | |
def get_firestore_client() -> firestore.Client: | |
""" | |
Return a firestore Client, connects to an emulator if FIREBASE_FIRESTORE_EMULATOR_ADDRESS is set | |
eg, using https://firebase.google.com/docs/functions/local-emulator | |
firebase emulators:start --only firestore | |
:return: | |
""" | |
emulator_address = os.environ.get("FIREBASE_FIRESTORE_EMULATOR_ADDRESS") | |
if emulator_address: | |
dummy_project = "foo" | |
dummy_credentials = mock.MagicMock(spec=Credentials) | |
db = firestore.Client(project=dummy_project, credentials=dummy_credentials) | |
# hack - set the internal firestore api client to point at the emulator, | |
# used by ref: google.cloud.firestore_v1.client.Client._firestore_api | |
print(f"connecting to firestore emulator at {emulator_address}") | |
channel = grpc.insecure_channel(emulator_address) | |
transport = firestore_grpc_transport.FirestoreGrpcTransport(channel=channel) | |
db._firestore_api_internal = firestore_client.FirestoreClient(transport=transport) | |
else: | |
db = firestore.Client() | |
return db |
Also worth noting that this configuration is only good for testing rules for an unauthenticated user - I'm trying to figure out how to feed in a JWT that authenticates a given user so it can be used to test rules that use request.auth.uid
.
In the Node SDK this can be done as follows:
firebase.initializeTestApp({
projectId: "my-test-project",
auth: { uid: "alice", email: "[email protected]" }
});
https://firebase.google.com/docs/firestore/security/test-rules-emulator#run_local_tests
I think this is now obsolete, since https://github.com/googleapis/google-cloud-python/pull/8721/files it's now possible to connect to the firestore emulator as admin by just setting the following environment variables:
export FIRESTORE_EMULATOR_HOST=localhost:8080
# needs to be set otherwise so the client can determine project id, but it can be any string in google cloud project id format.
export GOOGLE_CLOUD_PROJECT=any-thing
Thank you @therefromhere! This is very useful for me 🙂
I'm waiting for the Firebase Authentication <-> python admin sdk integration. For those who are interested:
firebase/firebase-admin-python#531
Note:
firestore_client.FirestoreClient
is not process safe, since it can't be pickled.Maybe we can hack up a Mutex wrapper...