4

I'm using Pyrebase to receive data from a realtime database. Actually I can receive data directly, but I need only the latest record.

This is the realtime database:

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
vargaking
  • 51
  • 1
  • 7

1 Answers1

5

Assuming the largest key (4 here) is the most recent record's, here is how to directly retrieve it with pyrebase:

firebase = pyrebase.initialize_app(config)
db = firebase.database()

last_record = db.child('input').order_by_key().limit_to_last(1).get().val()

print(last_record)
# should print OrderedDict([('4', {'input1': ..., 'input2': ..., 'input3': ...})])

order_by_key orders in ascending order by default, and limit_to_last(1) ensures you only retrieve one record, being the last one in the query.

However there is a bug for calling order_by in the pyrebase library. Fortunately a fork of it, pyrebase4, has it fixed so ensure to use this one:

$ pip uninstall pyrebase && pip install pyrebase4
michaeldel
  • 2,204
  • 1
  • 13
  • 19
  • thank you very much, it works. Is there a mode to get it as a bit useable form, like 4 record input1 input2 input3? – vargaking May 02 '20 at 10:03
  • You can simply access them as any other `dict` or [OrderedDict](https://docs.python.org/3.8/library/collections.html#collections.OrderedDict), _e.g._ `input1 = last_record[0][1]['input1']` – michaeldel May 02 '20 at 16:01
  • I tried to use this code but I always get an error message – vargaking May 03 '20 at 16:34
  • I solved it. The problem was that I didn't converted it to a string. – vargaking May 03 '20 at 17:38