How to prevent anonymous keys on Firebase?

903 views Asked by At

I'm working on a chat project on the platform Raspberry PI 3, Openelec OS.

Trying to write to the DB and getting unwanted anonymous keys.

Firebase real-time DB

Unwanted key marked with yellow. Movie2 and it's keys and values are the wanted result, but I made it manually.

I only ask how can I prevent this anonymous random key to be there and how can I replace it with other key? (string, a movie name for example)

This is my code:

url = 'https://chat-example-97c62.firebaseio.com/Movie1.json'
postdata = {
    'date': str(time.asctime( time.localtime(time.time()) )),
    'temp': str("Hello from Kodi")
 }
req = urllib2.Request(url)
req.add_header('Content-Type','application/json')
data = json.dumps(postdata)

Thanks.

1

There are 1 answers

0
Mr. Phantom On BEST ANSWER

When you send a POST request to Firebase, it automatically generates a Key (Anonymous Key), if you want to use your own key you need to use a PATCH request, this is an example on Python 3:

def update_entry(user, message):

    my_data = dict()
    my_data["user"] = user
    my_data["message"] = message

    json_data = json.dumps(my_data).encode()
    request = urllib.requests.Request("https://<YOUR-PROJECT-ID>.firebaseio.com/movies/<REPLACE_THIS_WITH_YOUR_DESIRED_KEY>.json", data=json_data, method="PATCH")

    try:
        loader = urllib.request.urlopen(request)
    except urllib.error.URLError as e:
        message = json.loads(e.read())
        print(message["error"])
    else:
        print(loader.read())