Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing motor.MotorClient() connection

I want to know how to check that a Motor connection is successful. If i kill the mongod process and perform a:

con = motor.MotorClient(host,port)

I get "[W 150619 00:38:38 iostream:1126] Connect error on fd 11: ECONNREFUSED"

Makes sense since there's no server running. However because this isn't an exception I'm not sure how to check for this case?

I thought I could check the con.is_mongos however it seems it's always False (also stated in the documentation).

How do I check above error scenario?

like image 244
johhny B Avatar asked Sep 06 '25 03:09

johhny B


1 Answers

Although A. Jesse Jiryu Davis has a point. There are of course valid cases when you want to check your connection. For example, when you start your program and the user might have forgotten to start MongoDb. A nice error message is better than a long stacktrace.

Here is how you can check your connection:

import asyncio
import motor.motor_asyncio
async def get_server_info():
    # replace this with your MongoDB connection string
    conn_str = "<your MongoDB Atlas connection string>"
    # set a 5-second connection timeout
    client = motor.motor_asyncio.AsyncIOMotorClient(conn_str, serverSelectionTimeoutMS=5000)
    try:
        print(await client.server_info())
    except Exception:
        print("Unable to connect to the server.")
loop = asyncio.get_event_loop()
loop.run_until_complete(get_server_info())

Source: https://docs.mongodb.com/drivers/motor/#std-label-connect-atlas-motor-driver

like image 159
AV_Jeroen Avatar answered Sep 09 '25 03:09

AV_Jeroen