Search code examples
pythonfirebasegoogle-cloud-firestorevalueerrorkivymd

How to prevent from the value error which is appeared while getting data from firestore database in Python


I'm using firebase firestore database for my KivyMD project. In the program when a button is pressed the data should be saved in the database if they doesn't exist. It work successfully. But the problem is a ValueError is appeared when the user enters an existing email address and enter another email at second time as it is not valid. What can I do to prevent it?

The Error

ValueError: The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name.

The Code

def send_data(self, email, password):
    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore

    cred = credentials.Certificate("firestore.json")
    firebase_admin.initialize_app(cred)

    db = firestore.client()

    data = {
        "Email": email,
        "Password": password
    }

    query_email = db.collection(u'Users').where(u"Email", u"==", data["Email"]).get()
    if query_email:
        print('exist')
    else:
        print('does not exist')
        db.collection(u'Users').add(data)

Solution

  • Based on the error message, the problem is with the following lines:

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    cred = credentials.Certificate("firestore.json")
    firebase_admin.initialize_app(cred)
    
    db = firestore.client()
    

    If possible, move these lines outside of your function. You should initialize the db elsewhere and pass it to your function.

    def send_data(self, email, password, db):