Search code examples
pythonfirebasefirebase-realtime-databaseaws-lambdafirebase-admin

How to obtain DB Keys before push in Firebase Admin Python SDK


I am using Firebase Admin Python SDK in a AWS Lambda Function. I want to push in the DB multiple objects in a single update.

 for mess in arrayMessages:

    ...

    newMessageKey = root.child('.../messages').push().key

    messages_updates[newMessageKey] = {
            'author': 'Bob',
            'dateTime': d,
            'text': mess,
    }

    messagesKeys.append(newMessageKey)

    ...

root.child(''.../messages').set(messages_updates)

The "...push().key" method, immediately creates the key on the db (it would make sense then to move directly in one command, but lose the efficiency of the Updates). Doing the Updates without pushing, insert incremental integer keys (trivial sequence 0,1,2 ...)

Like the SDK for Android Client (designed to get the keys even offline), is there a solution to get the key even before the object is created on the DB?


Solution

  • As of sep. 2021 it is: https://firebase.google.com/docs/database/admin/save-data#getting-the-unique-key-generated-by-push

    Citing @JW_'s comment.

    Old Answer:

    It is not possible using the admin SDK. However there is a python port of the JS code that is used to generate the IDs client-side.

    Michael Lehenbauer from the firebase team described the implementation in a blog article. There you can also find a link to a GitHub gist of the implementation which in turn has a comment with a link to the python implementation above.