python firebase realtime listener

自闭症网瘾萝莉.ら 提交于 2019-11-27 17:01:31

问题


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. How can I do it? Thank a lot

my db is like simple list of data from 001 to 200:

"remote-controller"
001 -> 000
002 -> 020
003 -> 230

my code is:

from firebase import firebase
firebase = firebase.FirebaseApplication('https://remote-controller.firebaseio.com/', None)
result = firebase.get('003', None)
print result

回答1:


It looks like this is supported now (october 2018): although it's not documented in the 'Retrieving Data' guide, you can find the needed functionality in the API reference. I tested it and it works like this:

def listener(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

firebase_admin.db.reference('my/data/path').listen(listener)



回答2:


As you can see on the per-language feature chart on the Firebase Admin SDK home page, Python and Go currently don't have realtime event listeners. If you need that on your backend, you'll have to use the node.js or Java SDKs.




回答3:


You can use Pyrebase, which is a python wrapper for the Firebase API.

more info here:

https://github.com/thisbejim/Pyrebase

To retrieve data you need to use val(), example:

users = db.child("users").get()
print(users.val())



回答4:


As Peter Haddad suggested, you should use Pyrebase for achieving something like that given that the python SDK still does not support realtime event listeners.

import pyrebase

config = {
    "apiKey": "apiKey",
    "authDomain": "projectId.firebaseapp.com",
    "databaseURL": "https://databaseName.firebaseio.com",
    "storageBucket": "projectId.appspot.com"
}

firebase = pyrebase.initialize_app(config)

db = firebase.database()

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)


来源:https://stackoverflow.com/questions/49863708/python-firebase-realtime-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!