Reputation: 99
I have some python code running 24/7 on a server like so:
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
The above code keeps fetching data from the database over and over again and only runs the rest of the code if isImageToScan
is true. Is there a way to add a listener so that it triggers the code when there is a change to the value in the database instead of manually iterating through the loop over and over again like this?
A user here seems to have solved this using REST API, I am not familiar with REST API. How would I implement this in my code if the way mentioned in this post is the correct solution?
Upvotes: 0
Views: 2675
Reputation: 599341
Your code uses get
, which gets the data and immediately continues
To listen for data, follow the documentation on streaming updates. From there:
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)
This will open a single SSE connection, sending updates over HTTP.
Note that Firebase also has an Admin SDK for Python, which also support streaming updates through its listen
method.
Upvotes: 1