适用于python的Firestore侦听器

时间:2019-06-09 08:43:58

标签: python google-cloud-firestore

我想知道一种监听Firestore中文档中发生的任何更改的方法,例如添加新文档或删除文档。但是我找不到有关此问题的任何相关文档,因此请在发布代码段以帮助我之前是否有人使用过此文件。

为解决此问题,我进行了无限循环,每秒检查是否有任何更改,但是大约15分钟后,如果我收到太多请求错误

修改

使用On快照侦听器后,我的应用程序什么也没做,只是运行没有错误,然后终止,并且在代码下面,我已经使用过。

import firebase_admin
from firebase_admin import firestore , credentials

cred = credentials.Certificate("AdminSDK.json")
firebase_admin.initialize_app(cred)

db = firestore.client()


def on_snapshot(col_snapshot, changes, read_time):
    print(u'Callback received query snapshot.')
    print(u'Current cities in California: ')
    for change in changes:
        if change.type.name == 'ADDED':
            print(u'New city: {}'.format(change.document.id))
        elif change.type.name == 'MODIFIED':
            print(u'Modified city: {}'.format(change.document.id))
        elif change.type.name == 'REMOVED':
            print(u'Removed city: {}'.format(change.document.id))
col_query = db.collection(u'NeedClassification')
query_watch = col_query.on_snapshot(on_snapshot)

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,对我来说,根本原因是我没有通过在最后添加脚本来使脚本继续运行:

while True:
time.sleep(1)
print('processing...')

作为参考,我的整个代码和输出是:

import firebase_admin
import google.cloud
from firebase_admin import credentials, firestore
import time

print('Initializing Firestore connection...')
# Credentials and Firebase App initialization. Always required
firCredentials = credentials.Certificate("./key.json")
firApp = firebase_admin.initialize_app (firCredentials)

# Get access to Firestore
db = firestore.client()
print('Connection initialized')

def on_snapshot(doc_snapshot, changes, read_time):
    for doc in doc_snapshot:
        print(u'Received document snapshot: {}'.format(doc.id))

doc_ref = db.collection('audio').document('filename')
doc_watch = doc_ref.on_snapshot(on_snapshot)

# Keep the app running
while True:
    time.sleep(1)
    print('processing...')

输出(在添加循环之前,输出将在初始化连接时停止):

Initializing Firestore connection...
Connection initialized
Received document snapshot: filename
processing...
processing...
processing...
processing...
processing...
processing...
Received document snapshot: filename
processing...
processing...
# ...[and so on]

希望这会有所帮助。