如何在KivyMD Python项目中实现Firebase实时数据库的用户邮箱重复校验与数据存储控制
Hey there! Let's get that email duplication check working for your KivyMD and Firebase app. I'll walk you through modifying your code to meet your requirements, plus add some helpful improvements.
Step-by-Step Solution
First, let's fix the core logic: we need to check if the input email already exists in your Firebase Realtime Database before submitting new data. Here's the revised code with explanations:
1. Move Imports to the Top
It's better to import dependencies once at the start of your file instead of inside the function:
from firebase import firebase from kivymd.uix.dialog import MDDialog from kivymd.uix.button import MDFlatButton
2. Updated send_data Function
def send_data(self, email): # Initialize Firebase connection (consider moving this to your class __init__ for efficiency) firebase = firebase.FirebaseApplication("https://infinity-mode-default-rtdb.firebaseio.com/", None) # First validate the input: check if email is empty if not email.strip(): cancel_btn = MDFlatButton(text='Retry', on_release=self.close_checkpoint_dialogue) self.checkpoint_dialog = MDDialog( title='Access Denied', text="Invalid Username", buttons=[cancel_btn] ) self.checkpoint_dialog.open() return try: # Option 1: Fetch all users and check for duplicate (good for small datasets) users = firebase.get('Users', None) email_exists = False if users: # Loop through each user to check their email for _, user_data in users.items(): # Use .lower() to make the check case-insensitive (optional but user-friendly) if user_data.get('Email', '').strip().lower() == email.strip().lower(): email_exists = True break # Option 2: Use Firebase Query (more efficient for large datasets) # query = firebase.get( # 'Users', None, # params={'orderBy': '"Email"', 'equalTo': f'"{email.strip()}"'} # ) # email_exists = query is not None and len(query) > 0 if email_exists: # Show duplicate email alert ok_btn = MDFlatButton(text='OK', on_release=self.close_checkpoint_dialogue) self.checkpoint_dialog = MDDialog( title='Duplicate Email', text="该邮箱已被使用", buttons=[ok_btn] ) self.checkpoint_dialog.open() else: # Save the new email since it's unique data = {'Email': email.strip()} firebase.post('Users', data) # Optional: Show success message success_btn = MDFlatButton(text='OK', on_release=self.close_checkpoint_dialogue) self.checkpoint_dialog = MDDialog( title='Success', text="数据已成功保存", buttons=[success_btn] ) self.checkpoint_dialog.open() except Exception as e: # Handle unexpected errors (like network issues) retry_btn = MDFlatButton(text='Retry', on_release=self.close_checkpoint_dialogue) self.checkpoint_dialog = MDDialog( title='Error', text=f"无法连接到数据库: {str(e)}", buttons=[retry_btn] ) self.checkpoint_dialog.open()
Key Improvements & Notes
- Input Validation: Replaced
email.split() == []withnot email.strip()for cleaner, more reliable empty input checks. - Error Handling: Added a
try-exceptblock to catch issues like network failures, so your app won't crash unexpectedly. - Case-Insensitive Check: The
.lower()conversion ensures that emails likeUser@Example.comanduser@example.comare treated as duplicates (you can remove this if you need strict case sensitivity). - Efficient Query Option: For larger datasets, use the Firebase query (Option 2) instead of fetching all users. It directly filters matching emails from the database, saving bandwidth and time.
- Firebase Initialization: Consider moving the Firebase setup to your class's
__init__method so you don't reinitialize the connection every timesend_datais called.
Quick Tip
Make sure your Firebase Realtime Database rules allow read access to the Users node (otherwise the check will fail). For testing, you can set temporary rules:
{ "rules": { ".read": true, ".write": true } }
Just remember to tighten these rules for production!
内容的提问来源于stack exchange,提问作者Kusal Darshana

