python firebase realtime listener

前端 未结 6 1077
离开以前
离开以前 2020-12-05 16:47

Hi there I\'m new in python. I would like to implement the listener on my Firebase DB. When I change one or more parameters on the DB my Python code have to do something. Ho

6条回答
  •  春和景丽
    2020-12-05 17:28

    If Anybody wants to create multiple listener using same listener function and want to get more info about triggered node, One can do like this.

    Normal Listener function will get a Event object it has only Data, Node Name, Event type. If you add multiple listener and You want to differentiate between the data change. You can write your own class and add some info to it while creating object.

    class ListenerClass:
        def __init__(self, appname):
            self.appname = appname
    
        def listener(self, event):
            print(event.event_type)  # can be 'put' or 'patch'
            print(event.path)  # relative to the reference, it seems
            print(event.data)  # new data at /reference/event.path. None if deleted
            print(self.appname) # Extra data related to change add your own member variable
    

    Creating Objects:

    listenerObject = ListenerClass(my_app_name + '1')
    db.reference('PatientMonitoring', app= obj).listen(listenerObject.listener)
    
    listenerObject = ListenerClass(my_app_name + '2')
    db.reference('SomeOtherPath', app= obj).listen(listenerObject.listener)
    

    Full Code:

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import db
    
    # Initialising Database with credentials
    json_path = r'E:\Projectz\FYP\FreshOnes\Python\PastLocations\fyp-healthapp-project-firebase-adminsdk-40qfo-f8fc938674.json'
    my_app_name = 'fyp-healthapp-project'
    xyz = {'databaseURL': 'https://{}.firebaseio.com'.format(my_app_name),'storageBucket': '{}.appspot.com'.format(my_app_name)}
    
    cred = credentials.Certificate(json_path)        
    obj = firebase_admin.initialize_app(cred,xyz , name=my_app_name)
    
    # Create Objects Here, You can use loops and create many listener, But listener will create thread per every listener, Don't create irrelevant listeners. It won't work if you are running on machine with thread constraint
    
    listenerObject = ListenerClass(my_app_name + '1') # Decide your own parameters, How you want to differentiate. Depends on you
    db.reference('PatientMonitoring', app= obj).listen(listenerObject.listener)
    
    listenerObject = ListenerClass(my_app_name + '2')
    db.reference('SomeOtherPath', app= obj).listen(listenerObject.listener)
    

提交回复
热议问题