2014-06-18 53 views

回答

2

是的,嘗試/除非是檢查服務器是否啓動的良好(pythonic)方式。然而,最好趕特定錯誤時拋出(ConnectionFailure):

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

對於pymongo的新版本,從MongoClient文檔:

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") 

可以初始化MongoClient與serverSelectionTimeoutMS避免等待20秒或所以在代碼之前引發異常:

client = MongoClient(serverSelectionTimeoutMS=500) # wait 0.5 seconds in server selection 
相關問題