简体   繁体   English

python firebase实时监听器

[英]python firebase realtime listener

Hi there I'm new in python.嗨,我是 Python 新手。 I would like to implement the listener on my Firebase DB.我想在我的 Firebase 数据库上实现监听器。 When I change one or more parameters on the DB my Python code have to do something.当我更改数据库上的一个或多个参数时,我的 Python 代码必须执行某些操作。 How can I do it?我该怎么做? Thank a lot非常感谢

my db is like simple list of data from 001 to 200:我的数据库就像从 001 到 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

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 .现在似乎支持此功能(2018 年 10 月) :尽管 “检索数据”指南中没有记录, 您可以在API 参考中找到所需的功能。 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)

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.正如Peter Haddad 所建议的,鉴于 python SDK 仍然不支持实时事件侦听器,您应该使用Pyrebase来实现类似的功能。

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)

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.正如您在Firebase Admin SDK 主页上的每种语言功能图表中所见,Python 和 Go 目前没有实时事件侦听器。 If you need that on your backend, you'll have to use the node.js or Java SDKs.如果您的后端需要它,则必须使用 node.js 或 Java SDK。

You can use Pyrebase , which is a python wrapper for the Firebase API.您可以使用Pyrebase ,它是 Firebase API 的 Python 包装器。

more info here:更多信息在这里:

https://github.com/thisbejim/Pyrebase https://github.com/thisbejim/Pyrebase

To retrieve data you need to use val() , example:要检索数据,您需要使用val() ,例如:

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

Python Firebase Realtime Listener Full Code : Python Firebase 实时侦听器完整代码:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

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
    
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)

db.reference('PatientMonitoring', app= obj).listen(listener)

Output:输出:

put
/
{'n0': '40', 'n1': '71'} # for first time its gonna fetch the data from path whether data is changed or not

put # On data changed 
/n1  
725

put # On data changed 
/n0
401

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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