如何防止 Python 中从 firestore 数据库获取数据时出现的值错误

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

我正在为我的 KivyMD 项目使用 firebase firestore 数据库。在程序中,当按下按钮时,如果数据不存在,则应将其保存在数据库中。它工作成功。但问题是当用户输入现有电子邮件地址并在第二次输入另一封电子邮件时出现 ValueError,因为它无效。我能做些什么来防止它?

错误

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.

代码

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)

根据错误消息,问题出在以下几行:

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()

如果可能,将这些行移到您的函数之外。您应该在别处初始化 db 并将其传递给您的函数。

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