使用 python 检测 firebase 实时数据库中的变化
Detect changes in firebase realtime database with python
我有一些 python 代码 运行 24/7 在这样的服务器上:
firebase = pyrebase.initialize_app(config)
db = firebase.database()
while True:
result = db.child("imgPostStatus").get()
isImageToScan = None
for elements in result.each():
isImageToScan = elements.val()
if isImageToScan:
#perform the rest of the code
#set isImageToScan to false in the DB
上面的代码一遍又一遍地从数据库中获取数据,只有在 isImageToScan
为真时才运行剩余的代码。有没有办法添加一个侦听器,以便在数据库中的值发生更改时触发代码,而不是像这样一遍又一遍地手动迭代循环?
一位用户 似乎已经使用 REST API 解决了这个问题,我不熟悉 REST API。如果 post 中提到的方法是正确的解决方案,我将如何在我的代码中实现它?
您的代码使用 get
,它获取数据并立即继续
要收听 数据,请按照 streaming updates 上的文档进行操作。从那里:
def stream_handler(message):
print(message["event"]) # put
print(message["path"]) # /-K7yGTTEp7O549EzTYtI
print(message["data"]) # {'title': 'Pyrebase', "body": "etc..."}
my_stream = db.child("posts").stream(stream_handler)
这将打开一个 SSE 连接,通过 HTTP 发送更新。
请注意,Firebase 也有一个 Admin SDK for Python, which also support streaming updates through its listen
method。
我有一些 python 代码 运行 24/7 在这样的服务器上:
firebase = pyrebase.initialize_app(config)
db = firebase.database()
while True:
result = db.child("imgPostStatus").get()
isImageToScan = None
for elements in result.each():
isImageToScan = elements.val()
if isImageToScan:
#perform the rest of the code
#set isImageToScan to false in the DB
上面的代码一遍又一遍地从数据库中获取数据,只有在 isImageToScan
为真时才运行剩余的代码。有没有办法添加一个侦听器,以便在数据库中的值发生更改时触发代码,而不是像这样一遍又一遍地手动迭代循环?
一位用户
您的代码使用 get
,它获取数据并立即继续
要收听 数据,请按照 streaming updates 上的文档进行操作。从那里:
def stream_handler(message):
print(message["event"]) # put
print(message["path"]) # /-K7yGTTEp7O549EzTYtI
print(message["data"]) # {'title': 'Pyrebase', "body": "etc..."}
my_stream = db.child("posts").stream(stream_handler)
这将打开一个 SSE 连接,通过 HTTP 发送更新。
请注意,Firebase 也有一个 Admin SDK for Python, which also support streaming updates through its listen
method。