I Create A RealTime DataBase And I Start Pushing some Data Like Username and Id and Date ext.
But I need to Check if This ID is Exist in my Database or not How Can I do it.
This is my Code:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
cred_obj = firebase_admin.credentials.Certificate('firebase_credentials.json')
default_app = firebase_admin.initialize_app(cred_obj, {
'databaseURL': 'My DataBase URL'})
ref = db.reference("/Logs")
ref.child(user.name).set({
'Name' : user.full_name,
'ID' : str(user.id),
'Date' : str(update.message.date.astimezone(pytz.timezone('Asia/Damascus')).strftime("%d-%b-%Y")),
'Time' : str(update.message.date.astimezone(pytz.timezone('Asia/Damascus')).strftime("%H:%M:%S"))
})
I need to Check if this name or this ID Exist I won't Update the Database..
CodePudding user response:
To conditionally write a value to a path in the database, you can use a transaction.
In your case that's look something like:
def set_initial_value(current_value):
return current_value if current_value else {
'Name' : user.full_name,
'ID' : str(user.id),
'Date' : str(update.message.date.astimezone(pytz.timezone('Asia/Damascus')).strftime("%d-%b-%Y")),
'Time' : str(update.message.date.astimezone(pytz.timezone('Asia/Damascus')).strftime("%H:%M:%S"))
}
ref = db.reference("/Logs")
try:
ref.child(user.name).transaction(set_initial_value);
print('Transaction completed')
except db.TransactionAbortedError:
print('Transaction failed to commit')