Does mongoengine provide any method for checking whether the connection is ok?
TonyYanOnFire opened this issue · 1 comments
TonyYanOnFire commented
ChatGPT gives me these codes, but looks like ping
is not callable
from mongoengine import connect, get_connection
# Connect to a MongoDB database
connect('my_database')
# Get the current connection object
connection = get_connection()
# Check the status of the connection
if connection.ping():
print('Connection is active and working properly')
else:
print('Connection is not active or is not working properly')
bagerard commented
MongoEngine itself doesn't provide this but you can access the underlying Pymongo MongoClient instance with
E.g
from mongoengine import connect, get_db
mongo_client = connect()
# or if you need to get the client from another place in your code
db = get_db()
mongo_client = db.client
try:
mongo_client.server_info()
print('Connection is active and working properly')
except ServerSelectionTimeoutError:
print('Connection is not active or is not working properly')