我怎么能告诉mongodb服务器了?

时间:2014-06-18 19:06:04

标签: python mongodb

如何告诉mongodb服务器已启动并运行python?我目前使用

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

或者我可以使用的pymongo函数有更好的方法吗?

2 个答案:

答案 0 :(得分:3)

是的,尝试/ except是检查服务器是否正常的良好(pythonic)方式。但是,最好抓住特定的重复(ConnectionFailure):

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

答案 1 :(得分:2)

对于新版本的pymongo,来自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")

您可以使用serverSelectionTimeoutMS初始化MongoClient,以避免在代码引发异常之前等待20秒左右:

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