【问题标题】:Firestore Listeners for pythonpython的Firestore监听器
【发布时间】:2019-10-24 01:47:11
【问题描述】:

我想知道一种方法来监听 Firestore 中文档中发生的任何更改,例如添加新文档或删除文档。但是我找不到任何关于这个问题的相关文档,所以请如果有人在发布代码 sn-ps 之前使用它来帮助我。

为了克服这个问题,我做了一个无限循环来检查是否每秒有任何变化,但大约 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)

【问题讨论】:

标签: python google-cloud-firestore


【解决方案1】:

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

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]

希望这会有所帮助。

【讨论】:

  • 如何只收听 on_create 并获取插入的文档数据?
  • 我尝试了您的解决方案,但它使用了很多网络,所以我使用节点 JS API 来监听更改,当它发现更改时,它会生成一个 python 进程并将文档 ID 作为参数传递,以便python 文件随心所欲
  • 不应该使用很多网络,因为 Firestore 架构应该避免它。 oy是怎么测试的? @MohamedNashaat
  • 非常感谢@ecdemomaniaKay 的回答,我遇到了同样的问题。你现在是否有办法等待第一个快照然后继续代码?
猜你喜欢
  • 2023-04-10
  • 2020-12-04
  • 2018-03-27
  • 2021-06-04
  • 2019-10-28
  • 2020-12-02
  • 1970-01-01
  • 2021-10-05
  • 2018-06-09
相关资源
最近更新 更多