我正在尝试在python上设置Firestore on_snapshot侦听器。 但是,当我运行该程序时,它无需执行任何操作即可结束运行,更不用说听了。
我想念什么?
我试图一次性读取即.get(),并且它起作用了,所以我知道这不是程序包/凭据问题。
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred)
db = firestore.client()
doc_ref = db.collection(u'someCollection').document(u'someDoc')
def on_snapshot (doc_snapshot, changes, read_time):
for doc in doc_snapshot:
print(u'New doc data: {}'.format(doc.id))
doc_watch = doc_ref.on_snapshot(on_snapshot)
答案 0 :(得分:2)
似乎您试图以脚本形式运行此代码,该脚本似乎在执行回调函数之前已终止。因此,请尝试使from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'apps.myapp'
def ready(self):
try:
import apps.myapp.signals # noqa F401
import apps.myapp.tasks
except ImportError:
pass
对象的寿命足够长。
例如,使用doc_watch
:
sleep
别忘了在结尾处from time import sleep
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred)
db = firestore.client()
doc_ref = db.collection(u'someCollection').document(u'someDoc')
def on_snapshot (doc_snapshot, changes, read_time):
global count
for doc in doc_snapshot:
print(u'New doc data: {}'.format(doc.id))
doc_watch = doc_ref.on_snapshot(on_snapshot)
sleep(3)
doc_watch.unsubscribe()
;)。