I'm trying to create a Python function that generates a valid key in my Firebase Realtime Database (using the same logic as other keys, ensuring no collision and chronological order).
Something like this:
def get_new_key() -> str:
return db.reference(app=firebase_app).push().key
print(get_new_key())
# output: '-OOvws9uQDq9Ozacldjr'
However, doing this actually creates the node with an empty string value, as specified in the doc. Is there any way to grab the key without adding anything to the database?
My only thought right now would be to reimplement myself their key generation algorithm, but this looks overkill and not future-proof if this algorithm changes.
You're right, each time you call push(value='')
a child node in the Realtime Database will be created. If you are calling the function without passing a value, the default string that will be used for writing the data will be an empty string.
As far as I know, the Firebase SDKs for Python does not publicly expose a push()
function that only generates the IDs. So the only option that you have would be to use the algorithm that is present below:
It is written in JavaScript, but I think that you can adapt it very easily to Python. This algorithm is very stable, and I don't think that it will change because many clients (Android, iOS, Web) depend on it.
Here's a the Python implementation of Firebase’s generatePushID()
(not tested):
import time
import random
PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'
def generate_push_id():
now = int(time.time() * 1000)
time_stamp_chars = []
for _ in range(8):
time_stamp_chars.append(PUSH_CHARS[now % 64])
now //= 64
time_stamp_chars.reverse()
push_id = ''.join(time_stamp_chars)
for _ in range(12):
push_id += random.choice(PUSH_CHARS)
return push_id