Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Retrieve Data from Firebase using Python

I'm new to Python and I would like to connect to Firebase using Python. I can successfully add and modify Firebase using put() and patch(), but I can't find a way to retrieve my data from Firebase.

Code:

import serial
import time
import requests
import json

firebase_url = 'https://testing1639.firebaseio.com'

#Connect to Serial Port for communication
ser = serial.Serial('/dev/ttyUSB0', 9600)

#Setup a loop to send temperature values at fixed intervals in seconds
fixed_interval = 2

while 1:
    try:
         #Temperature value obtained from Arduino + LM35 Temp Sensor
         temperature_c = ser.readline()
         #Current time and date
         time_hhmmss = time.strftime('%H:%M:%S')
         date_mmddyyyy = time.strftime('%d/%m/%Y')

         #Current location name
         temperature_location = 'Mumbai-Kandivali' ;

         print temperature_c + ',' + time_hhmmss + ',' + date_mmddyyyy + ',' + temperature_location

         #Insert record
         data = {'date':date_mmddyyyy,'time':time_hhmmss,'value':temperature_c}

         result = requests.post(firebase_url + '/' + temperature_location + '/temperature.json', data=json.dumps(data))

         #Insert record
         print 'Record inserted. Result Code = ' + str(result.status_code) + ',' + result.text
         time.sleep(fixed_interval)

    except IOError:
        print('Error! Something went wrong.')
        time.sleep(fixed_interval)

How can I modify it to retrieve the data?

like image 956
Sahar Alsadah Avatar asked Sep 08 '26 15:09

Sahar Alsadah


1 Answers

Installation

pip install firebase

Python Version

Firebase was written for python 3 and above and will not work correctly with python 2.

Add Firebase to your Application

Your Google's Firebase configuration data can be found on Firebase > Settings > Project Settings Scroll to bottom > Add to web app > config

For use with only user based authentication we can create the following configuration:

from firebase import Firebase

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

firebase = Firebase(config)

Authentication

The sign_in_with_email_and_password() method will return user data including a token you can use to adhere to security rules.

Each of the following methods accepts a user token: get(), push(), set(), update(), remove() and stream().

# Get a reference to the auth service
auth = firebase.auth()

# Log the user in
user = auth.sign_in_with_email_and_password(email, password)

# Get a reference to the database service
db = firebase.database()

# data to save
data = {
    "name": "Joe Tilsed"
}

# Pass the user's idToken to the push method
results = db.child("users").push(data, user['idToken'])

Database

You can build paths to your data by using the child() method.

db = firebase.database()
db.child("users").child("Joe")

Save Data

push

To save data with a unique, auto-generated, timestamp-based key, use the push() method.

data = {"name": "Joe Tilsed"}
db.child("users").push(data)
set

To create your own keys use the set() method. The key in the example below is "Joe".

data = {"name": "Joe Tilsed"}
db.child("users").child("Joe").set(data)
update

To update data for an existing entry use the update() method.

db.child("users").child("Joe").update({"name": "Joe W Tilsed"})
remove

To delete data for an existing entry use the remove() method.

db.child("users").child("Joe").remove()

Retrieve Data

val

Queries return a FirebaseResponse object. Calling val() on these objects returns the query data.

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

>> {"Joe": {"name": "Joe Tilsed"}, "Syd": {"name": "Sydney Cox"}}
key

Calling key() returns the key for the query data.

user = db.child("users").get()
print(user.key())

>> users
each

Returns a list of objects on each of which you can call val() and key().

all_users = db.child("users").get()
for user in all_users.each():
    print(user.key())

    >> Joe 

    print(user.val())   

    >> {name": "Joe Tilsed"}
get

To return data from a path simply call the get() method.

all_users = db.child("users").get()

Hope this helps. Full docs: https://pypi.org/project/firebase/

like image 148
Joe Tilsed Avatar answered Sep 11 '26 06:09

Joe Tilsed