Reputation: 1452
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?
Upvotes: 4
Views: 2940
Reputation: 101
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
Upvotes: 2
Reputation: 24007
Generally, the answer is don't. Don't check if a connection to MongoDB is working. You might find out that it's working right now, but the next operation might fail anyway--your sysadmin might pull your cable, the server crashes, whatever. Since you need to handle errors later in your application no matter, there's no point checking ahead of time whether Motor has connected successfully or not.
If you insist on this pointless check, even knowing that it gains you nothing, then you could do:
@gen.coroutine
def am_i_momentarily_connected_to_mongodb():
yield MotorClient().admin.command('ismaster')
If your IOLoop has already started and you're in a coroutine you can then do:
yield am_i_momentarily_connected_to_mongodb()
Or if you haven't started the loop yet:
IOLoop.instance().run_sync(am_i_momentarily_connected_to_mongodb)
But like I said, it's the nature of distributed systems that discovering a server is available now doesn't tell you anything certain about what will happen next.
Upvotes: 1