How to detect changes in firebase child with python?

前端 未结 3 836
醉梦人生
醉梦人生 2021-01-03 15:31

I have some troubles with this application. What I need is that If I detect a change in the database (FIREBASE) particularly in \'sala\' and \'ventilacion\' nodes the functi

3条回答
  •  粉色の甜心
    2021-01-03 15:37

    I was working on the same thing so according to current updates on pyrebase and learning from above posted answers, I got this running perfectly.(Please make sure your python is upgraded from python2 to python3 for running pyrebase and firebase-admin)

    import firebase_admin
    import pyrebase
    from firebase_admin import credentials
    
    config = {
        "apiKey": "",
        "authDomain": "",
        "databaseURL": "",
        "projectId": "",
        "storageBucket": "",
        "serviceAccount": "path to the service account json file you downloaded",
        "messagingSenderId": "",
        "appId": "",
        "measurementId": ""
    }
    
    firebase = pyrebase.initialize_app(config)
    storage = firebase.storage()
    cred = credentials.Certificate("path to downloaded json file")
    
    firebase_admin.initialize_app(cred, {
        "databaseURL": "same as config",
        "databaseAuthVariableOverride": None
    })
    db = firebase.database()
    
    def ignore_first_call(fn):
        called = False
    
        def wrapper(*args, **kwargs):
            nonlocal called
            if called:
                return fn(*args, **kwargs)
            else:
                called = True
                return None
        return wrapper
    
    def stream_handler(message):
        ab = str(1)
        all_videos = storage.child("videos/").list_files() #node where files are
    
        path_on_local = "local path to save the downloads"
        print(message["event"]) # put
        print(message["path"]) # /-K7yGTTEp7O549EzTYtI
        print(message["data"]) # {'title': 'Pyrebase', "body": "etc..."}
    
        node = str(message["path"]).split('/')[-2] 
        property = str(message["path"]).split('/')[-1]
        value = message["data"]
    
        if (message["event"] == "put"):
            for videos in all_videos:
                try:
                    print(videos.name)
                    z = storage.child(videos.name).get_url(None)
                    storage.child(videos.name).download(path_on_local + "/" + ab + ".mp4")
                    x = int(ab)
                    ab = str(x + 1)
                except:
                    print('Download Failed')
    
        else:
            print("error")
    
    my_stream = db.child("videos").stream(stream_handler)
    

提交回复
热议问题