python - python的Firestore监听器
问题描述
我想知道一种方法来监听 Firestore 中文档中发生的任何更改,例如添加新文档或删除文档。但是我找不到有关此问题的任何相关文档,因此请如果有人在发布代码片段以帮助我之前使用过此文档。
为了克服这个问题,我做了一个无限循环来检查每秒是否有任何变化,但大约 15 分钟后,如果让我出错太多请求
编辑
在使用 On snapshot listener 之后,我的应用程序什么都不做,它只是运行而没有错误,然后终止并在我使用的代码下方。
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)
解决方案
我有同样的问题,对我来说根本原因是我没有通过在最后添加这个来让脚本继续运行:
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]
希望这可以帮助。
推荐阅读
- c - 在扫描仪中递归地跳过嵌套注释
- ios - 如何在我们的项目中使用指令框架
- html - 在不使用外部库的情况下显示 pdf 文件
- vim - 如何更改 Vim 中差异的背景颜色?
- reactjs - 如何将选定的日期(值)从反应日历传递到另一个组件?
- pine-script - Pine 脚本 if 运算符
- gradle - IntelliJ 上的 Gradle 在所有任务完成执行后等待大约 20 秒
- python - 从 yml 文件创建环境的错误报告
- python - 如何在同一个 docker-compose 中连接到远程 Selenium 驱动程序?
- android - Android Studio 在添加新视图、新布局或新可绘制对象后抛出异常