'Python firebase_admin hangs when connecting to firestore emulator
I am unable to connect to firestore emulator from python. Connecting and writing documents to a real project works fine, but when setting the env. variable "FIRESTORE_EMULATOR_HOST" the set-function never resolves. The code:
os.environ["FIRESTORE_EMULATOR_HOST"]="localhost:8081"
os.environ["GCLOUD_PROJECT"]="my_project"
cred = credentials.Certificate('./firebase_cert.json')
default_app = firebase_admin.initialize_app(cred)
db = firestore.client()
doc_ref = db.collection(u'test').document()
doc_ref.set({
u'hello': "test"
})
print("Document stored successfully.")
My firebase.json:
{
"emulators": {
"firestore": {
"port": 8081
},
"ui": {
"enabled": true
} }
}
What could cause this?
UPDATE: I tried different things to figure out if this is a port issue and got the following in firebase-debug.log.
Set port to 8080 in firebase.json:
Jul 08, 2021 12:42:50 PM io.gapi.emulators.netty.NotFoundHandler handleRequest INFO: Unknown request URI: /app/agents/protocols
Set port to 8081 in firebase.json:
Jul 08, 2021 12:42:00 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead INFO: Detected non-HTTP/2 connection.
Not set port at all in firebase.json (force default port)
Jul 08, 2021 12:46:06 PM io.gapi.emulators.netty.NotFoundHandler handleRequest INFO: Unknown request URI: /app/agents/protocols
I dug into the google cloud package and found that the code at least executes until this point (line 821 in venv/Lib/site-packages/google/cloud/firestore_v1/services/firestore/client.py):
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
Solution 1:[1]
Downgraded the firebase-admin SDK from 5.0.2 to 4.5.1 and the downgrade fixed the issue for me.
Solution 2:[2]
I was able to get this to work by using the LAN's IP address for my machine instead of localhost or 127.0.0.1. This has worked for me in the past for other inconsistent behavior with the emulator as well. Everything else as far as config goes is identical to the code sample provided in the question. The JSON file I used for the credential was from my real Firebase project.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Harvey |
| Solution 2 | Dharman |
