简体   繁体   中英

Detect changes in firebase realtime database with python

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM