python的Firestore侦听器

2024-04-19 15:48:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何监听Firestore中文档中发生的任何更改,例如添加新文档或删除文档。但我找不到任何有关这件事的相关文档,所以如果有人在发布代码片段之前使用了这一点来帮助我。

为了克服这个问题,我做了一个无限循环来检查每秒钟是否有任何更改,但是在大约15分钟之后,如果让我收到错误的请求太多

编辑

在使用了On-snapshot侦听器之后,我的应用程序不做任何事情,它只是运行而没有错误,然后终止并低于代码,我已经使用了。

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)

Tags: name文档idformatcityadminontype
1条回答
网友
1楼 · 发布于 2024-04-19 15:48:20

我也遇到了同样的问题,根本原因是我没有通过在末尾添加以下内容来让脚本继续运行:

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

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

^{pr2}$

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

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

希望这有帮助。在

相关问题 更多 >