简体   繁体   中英

How can I tell the mongodb server is up?

How can I tell the mongodb server is up and running from python? I currently use

try:
    con = pymongo.Connection()
except Exception as e:
    ...

Or is there a better way in pymongo functions I can use?

Yes, try/except is a good (pythonic) way to check if the server is up. However, it's best to catch the specific excpetion ( ConnectionFailure ):

try:
    con = pymongo.Connection()
except pymongo.errors.ConnectionFailure:
    ...

For new versions of pymongo, from MongoClient docs:

from pymongo.errors import ConnectionFailure
client = MongoClient()
try:
    # The ismaster command is cheap and does not require auth.
    client.admin.command('ismaster')
except ConnectionFailure:
    print("Server not available")

You can init MongoClient with serverSelectionTimeoutMS to avoid waiting for 20 seconds or so before code it raises exception:

client = MongoClient(serverSelectionTimeoutMS=500)  # wait 0.5 seconds in server selection

Add the following headers:

from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError, OperationFailure

Create the connection with MongoDB from Python:

mongoClient = MongoClient("mongodb://usernameMongo:passwordMongo@localhost:27017/?authMechanism=DEFAULT&authSource=database_name", serverSelectionTimeoutMS=500)

Validations

try:
    if mongoClient.admin.command('ismaster')['ismaster']:
        return "Connected!"
except OperationFailure:
    return ("Database not found.")
except ServerSelectionTimeoutError:
    return ("MongoDB Server is down.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM