0
我怎麼能告訴mongodb服務器啓動並從python運行?我目前使用我如何告訴mongodb服務器啓動?
try:
con = pymongo.Connection()
except Exception as e:
...
或者是否有更好的方法可以使用pymongo函數?
我怎麼能告訴mongodb服務器啓動並從python運行?我目前使用我如何告訴mongodb服務器啓動?
try:
con = pymongo.Connection()
except Exception as e:
...
或者是否有更好的方法可以使用pymongo函數?
是的,嘗試/除非是檢查服務器是否啓動的良好(pythonic)方式。然而,最好趕特定錯誤時拋出(ConnectionFailure
):
try:
con = pymongo.Connection()
except pymongo.errors.ConnectionFailure:
...
對於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