简体   繁体   English

如何用 python 检测 firebase child 的变化?

[英]How to detect changes in firebase child with python?

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 function do what it have to do.我需要的是,如果我检测到数据库 (FIREBASE) 发生变化,特别是在“sala”和“ventilacion”节点中,该函数将执行它必须执行的操作。 If there isn't any change in the database it would not do nothing.如果数据库中没有任何变化,它就什么都不做。 I am using python and pyrebase library.我正在使用 python 和 pyrebase 库。 Here is the code.这是代码。 Thank you very much for you help.非常感谢你的帮助。

import pyrebase
import serial
import time
config = {
    #firebase configurations
}

firebase = pyrebase.initialize_app(config)

db = firebase.database()
def ReconfiguracionFabrica():
    ser.write('AT')
    time.sleep(0.2)
    ser.write('AT+RENEW')
    time.sleep(0.3)

def ConfiguracionMaster():
    time.sleep(0.5)
    ser.write('AT+IMME1')
    time.sleep(0.350)
    ser.write('AT+ROLE1')
    time.sleep(0.2)     

ser = serial.Serial(port="/dev/ttyAMA0", baudrate=9600, timeout=1)
ReconfiguracionFabrica()
time.sleep(0.1)
ConfiguracionMaster()
time.sleep(0.1)

print "**********   INICIO  *************"

ser.flushInput()
contador = 0
prender = ''
ventilacion1 = ''
checkeo = ''

while True:
    #if db.child("sala").: # It is the line where would be the conditional that allows me to detect any change only in the sala's node.
        salidaLed1 = db.child("sala").get()
        ser.write('AT')
        time.sleep(0.1)
        ser.write('AT+CON508CB16A7014')
        time.sleep(0.1)
        if salidaLed1.val() == True:
            prender = ";"
        if salidaLed1.val() == False:
            prender = ","

        ser.write('luz: %s \n' %(prender))
        print ('luz: %s \n' %(prender))
        time.sleep(1)
        ser.read(checkeo)
        if checkeo == 'j':
            ReconfiguracionFabrica()
            time.sleep(0.1)
            ConfiguracionMaster()

Question : How to detect changes in firebase child问题:如何检测 firebase child 的变化


Note : All Examples use Public Access注意:所有示例都使用公共访问

  1. Setup Example Data and verify it's readable.设置示例数据并验证其可读性。
    This hase to be done once !这必须做一次

    在此处输入图像描述

     temperature_c = 30 data = {'date':time.strftime('%Y-%m-%d'), 'time':time.strftime('%H:%M:%S'), 'temperature':temperature_c} db.child('public').child('Device_1').set(data) response = db.child('public').child('Device_1').get() print(response.val())
  2. Create First Script doing Updates:创建第一个执行更新的脚本:

     for t in [25, 26, 27, 28, 29, 30, 31, 32, 33, 35]: temperature_c = t data = {'date':time.strftime('%Y-%m-%d'), 'time':time.strftime('%H:%M:%S'), 'temperature':temperature_c} db.child('public').child('Device_1').update(data) time.sleep(60)
  3. Create Second Script with Stream Handler使用流处理程序创建第二个脚本

    def stream_handler(message): print('event={m[event]}; path={m[path]}; data={m[data]}'.format(m=message)) my_stream =db.child('public').child('Device_1').stream(stream_handler) # Run Stream Handler forever while True: data = input("[{}] Type exit to disconnect: ".format('?')) if data.strip().lower() == 'exit': print('Stop Stream Handler') if my_stream: my_stream.close() break
  4. Run Stream Handler Script:运行流处理程序脚本:

    Response Output from def stream_handler after startup (Initial Data):启动后def stream_handler的响应输出(初始数据):

     event="put"; path=/; data={'Device_1': {'temperature': 30, 'time': '13:34:24', 'date': '2017-07-20'}}
  5. Run Updater Script:运行更新程序脚本:

  6. Watch Output from Stream Handler Script观察流处理器脚本的输出

    Response Output from def stream_handler after First Update Data:首次更新数据后def stream_handler的响应输出:

     event=patch; path=/Device_1; data={'temperature': 25, 'time': '13:49:12'}

Tested with Python: 3.4.2用 Python 测试:3.4.2


Pyrebase Pyrebase
streaming串流

You can listen to live changes to your data with the stream() method.您可以使用 stream() 方法收听数据的实时更改。

 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)

You should at least handle put and patch events.您至少应该处理 put 和 patch 事件。 Refer to "Streaming from the REST API" for details.有关详细信息,请参阅“从 REST API 流式传输”。

I know this post is 2 years old but hope this helps.我知道这篇文章已有 2 年历史,但希望对您有所帮助。 Try using firebase_admin module.尝试使用 firebase_admin 模块。

Use this command - pip install firebase-admin使用此命令 - pip install firebase-admin

I too had a requirement where I needed to check for changes made to the Firebase database.我也有一个要求,我需要检查对 Firebase 数据库所做的更改。 I referred here在这里提到

Following is a sample code based on your question which you can refer from and try it out.以下是基于您的问题的示例代码,您可以参考并尝试一下。

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db


cred = credentials.Certificate("path/to/serviceAccountKey.json")
firebase_admin.initialize_app(cred, {
    'databaseURL': 'https://example.firebaseio.com',
    'databaseAuthVariableOverride': None
})


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


@ignore_first_call
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

    node = str(event.path).split('/')[-2] #you can slice the path according to your requirement
    property = str(event.path).split('/')[-1] 
    value = event.data
    if (node=='sala'):
        #do something
    elif (node=='ventilacion'):
        #do something
    else:
        #do something else


db.reference('/').listen(listener)

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)我正在做同样的事情,所以根据 pyrebase 的当前更新并从上面发布的答案中学习,我完美地运行了它。(请确保你的 python 从 python2 升级到 python3 以运行 pyrebase 和 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)

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

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