简体   繁体   中英

How to listen to firebase database changes using python?

I'm trying to connect IFTTT service with firebase using webhooks. For that, I have built a python server on pythonanywhere using Flask. And I was successful in doing that but I wanted to listen to the database changes every time data changes in the node without triggering the IFTTT every time. For that I used the while loop and it was working but the problem arises when I try to change the node I want to listen to from IFTTT.

from flask import Flask
from flask import request
import requests

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello!'


@app.route("/SENSORS", methods=["POST","GET"])
def handler1():
    val1= [0,0]

while True:
    username1 = request.get_data()
    username1 = username1.decode("utf-8")
    result1 = [x.strip() for x in username1.split(',')]
    print(result1)

    r1 = requests.get('https://myproject-024.firebaseio.com/USERS/DATA.json')    
    r2 = r1.text                                    #Converting it into text
    r3 = [x.strip() for x in r2.split('"')]         #Removing double quotes
    print(r3)

    #Swapping values to compare the previous and current value
    val1[1] = r2
    val1[1],val1[0] = val1[0],val1[1]

    requests.patch('https://myproject-024.firebaseio.com/USERS.json', json = { "SENSOR" : "1"} )


        if val1[0]!=val1[1]:
            responce = {"value1":"DATA1","value2":"DATA2","value3":"DATA3"}
            requests.post('https://maker.ifttt.com/trigger/USERS/with/key/, data=responce)

You're using the Firebase REST API to get data from the Realtime Database. The way you're using it now, the REST API provides a basic request/response model and always returns the data at the location you requested.

To check for updates on the data, you can request and pass an ETag . Using an ETag you can prevent getting the same data multiple times (saving bandwidth), but it won't give you live updates of changes to the data.

To listen for realtime updates to data at the location over regulat HTTP, you can use the REST streaming API , which uses server-sent events (SSE) to tell the client of updates. You'll note that this API is very different from what you're doing now, so you'll need to change quite a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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