Using Firebase with Python via Pyrebase - LabMazurokCom/Blockchain GitHub Wiki
We currently use pyrebase library.
firebase = pyrebase.initialize_app(config) # **CONFIG WILL BE EXPLAINED LATER**
db = firebase.database()
- Creating path root->'level1'->'level2' without adding data:
db.child('level1').child('level2')
- Getting all keys on the path root->'level1'->'level2':
ans = db.child('level1').child('level2').shallow().get().val() # <class 'dict_keys'>
- Example with key() and val()
Code:
db.child('level1').remove()
db.child('level1').child('level2').push({'a': 1, 'b': 2})
db.child('level1').child('level2').push({'a': 3, 'b': 5})
db.child('level1').child('level2').push({'a': 2, 'b': 0})
ans = db.child('level1').get()
print(ans.key())
print(ans.val())
ans = db.child('level1').child('level2').get()
print(ans.key())
print(ans.val())
ans = db.child('level1').child('level2').shallow().get()
print(ans.key())
print(ans.val())
Result:
level1
OrderedDict([('level2', {'-LB0rqYKt__lM3UHdFLq': {'a': 1, 'b': 2}, '-LB0rqpS3c63IJS6G8St': {'a': 3, 'b': 5}, '-LB0rqyqateehFDmSkt9': {'a': 2, 'b': 0}})])
level2
OrderedDict([('-LB0rqYKt__lM3UHdFLq', {'a': 1, 'b': 2}), ('-LB0rqpS3c63IJS6G8St', {'a': 3, 'b': 5}), ('-LB0rqyqateehFDmSkt9', {'a': 2, 'b': 0})])
level2
dict_keys(['-LB0rqYKt__lM3UHdFLq', '-LB0rqpS3c63IJS6G8St', '-LB0rqyqateehFDmSkt9'])
- Example with custom keys
Code:
i = 0
while i < 3:
i += 1
t = int(time() * 10**6)
db.child('level1').child(t).set({'a': randint(0,10), 'b': randint(0,10)})
ans = db.child('level1').shallow().get()
print(ans.val())
ans = db.child('level1').get()
print(ans.val())
Result:
dict_keys(['1524745508644952', '1524745508977775', '1524745509282224'])
OrderedDict([('1524745508644952', {'a': 7, 'b': 5}), ('1524745508977775', {'a': 10, 'b': 2}), ('1524745509282224', {'a': 5, 'b': 4})])
- Yet another way to add data
Code:
data = {}
i = 0
path = '/level1/level2/'
while i < 3:
i += 1
key = str(int(time() * 10**6))
data[path+key] = {'a': randint(0,10), 'b': randint(0,10)}
db.update(data)
print(db.shallow().get().val())
print(db.child('level1').shallow().get().val())
print(db.child('level1').child('level2').shallow().get().val())
print(db.child('level1').child('level2').get().val())
Result:
dict_keys(['level1'])
dict_keys(['level2'])
dict_keys(['1524749403229150', '1524749403229189', '1524749403229198'])
OrderedDict([('1524749403229150', {'a': 4, 'b': 1}), ('1524749403229189', {'a': 6, 'b': 10}), ('1524749403229198', {'a': 6, 'b': 4})])