client = MongoClient('localhost',27017)
db = client[DB_NAME]
def db_connect():
#connecting to a DB in mongoDB
try:
if client.get_database(DB_NAME):
print("Connection Successful!")
return True
except:
print("Please check your connection")
return False
def db_close():
print ("Connection Getting Closed")
client.close()
I am trying to achieve a task, only if the connection exists by pymongo, then return True so that the functions can proceed, else it should return False and a message to check connection. So that we don't proceed further.
How can I achieve this?
EDIT 1 : Accepted Solution
Successfully added user: {
"user" : "ash",
"roles" : [
{
"role" : "readWrite",
"db" : "myDB"
},
"clusterAdmin"
]
}
I added a user using the above code snippet and then used the following script.
DB_NAME = "myDB"
client = MongoClient('localhost',27017)
db = client[DB_NAME]
def db_connect():
#connecting to a DB in mongoDB
try:
if db.authenticate("ash","password"):
print("Connection Successful!")
return True
except:
print("Please check your connection")
return False
def db_close():
print ("Connection Getting Closed")
client.close()
if __name__ == "__main__":
db_connect()
db_close()
I have used this code snippet to connect to my DB Now getting connected to the DB I have the database in my PC and I am using Ubuntu 16.04.
You will probably have to use the authenticate method anyway inside connection function, so you could do it as following:
In [12]: client = MongoClient(DB_MACHINE, DB_PORT)
In [13]: db = client.db_name
In [16]: if db.authenticate(DB_USER, DB_PASS, source=DB_SOURCE):
# authenticated, do ...
else:
# not authenticated, not connected, do something else