如何检查MongoDB实例的客户端是否有效?

时间:2015-05-29 21:15:12

标签: python mongodb pymongo

特别是,我目前正在尝试使用以下函数检查与客户端的连接是否有效:

def mongodb_connect(client_uri):
    try:
        return pymongo.MongoClient(client_uri)
    except pymongo.errors.ConnectionFailure:
         print "Failed to connect to server {}".format(client_uri)

然后我使用这个函数:

def bucket_summary(self):
    client_uri = "some_client_uri"
    client = mongodb_connect(client_uri)
    db = client[tenant_id]
    ttb = db.timebucket.count() # If I use an invalid URI it hangs here

如果给出了无效的URI,有没有办法在最后一行捕获并抛出异常?我最初认为这就是ConnectionFailure的用途(因此在连接时可能会被捕获)但我错了。

如果我使用无效的URI运行程序,该程序无法运行,则发出KeyboardInterrupt会产生:

File "reportjob_status.py", line 58, in <module>
tester.summarize_timebuckets()
File "reportjob_status.py", line 43, in summarize_timebuckets
ttb = db.timebucket.count() #error
File "/Library/Python/2.7/site-packages/pymongo/collection.py", line   1023, in count
return self._count(cmd)
File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 985, in _count
with self._socket_for_reads() as (sock_info, slave_ok):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/Library/Python/2.7/site-packages/pymongo/mongo_client.py", line 699, in _socket_for_reads
with self._get_socket(read_preference) as sock_info:
File  "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/Library/Python/2.7/site-packages/pymongo/mongo_client.py", line 663, in _get_socket
server = self._get_topology().select_server(selector)
File "/Library/Python/2.7/site-packages/pymongo/topology.py", line 121, in select_server
address))
File "/Library/Python/2.7/site-packages/pymongo/topology.py", line 106, in select_servers
self._condition.wait(common.MIN_HEARTBEAT_INTERVAL)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 358, in wait
_sleep(delay)

5 个答案:

答案 0 :(得分:43)

pymongo.mongo_client.MongoClientserverSelectionTimeoutMS关键字参数控制驱动程序尝试连接服务器的时间。默认值为30秒。

将其设置为与典型连接时间¹兼容的极低值,以立即报告错误。您需要在此之后查询数据库以触发连接尝试:

>>> maxSevSelDelay = 1 # Assume 1ms maximum server selection delay
>>> client = pymongo.MongoClient("someInvalidURIOrNonExistantHost",
                                 serverSelectionTimeoutMS=maxSevSelDelay)
//                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>>> client.server_info()

这会引发pymongo.errors.ServerSelectionTimeoutError

¹显然serverSelectionTimeoutMS设置为0甚至可能在您的服务器具有非常低延迟的特定情况下工作(具有非常低的“本地”服务器的情况)轻载例如)

由您来捕获该异常并正确处理它。 喜欢的东西:

try:
    client = pymongo.MongoClient("someInvalidURIOrNonExistantHost",
                                     serverSelectionTimeoutMS=maxSevSelDelay)
    client.server_info() # force connection on a request as the
                         # connect=True parameter of MongoClient seems
                         # to be useless here 
except pymongo.errors.ServerSelectionTimeoutError as err:
    # do whatever you need
    print(err)

将显示:

No servers found yet

答案 1 :(得分:7)

您好了解是否建立了连接,您可以这样做:

Set oXMLRows = oXMLDoc.selectNodes("/myns:Workbook/myns:Worksheet/myns:Table/myns:Row")

答案 2 :(得分:1)

serverSelectionTimeoutMS对我不起作用(Python 2.7.12,MongoDB 3.6.1,pymongo 3.6.0)。 A. Jesse Jiryu Davisa GitHub issue中建议我们首先尝试套接字级连接作为试金石。这对我有用。

def throw_if_mongodb_is_unavailable(host, port):
    import socket
    sock = None
    try:
        sock = socket.create_connection(
            (host, port),
            timeout=1) # one second
    except socket.error as err:
        raise EnvironmentError(
            "Can't connect to MongoDB at {host}:{port} because: {err}"
            .format(**locals()))
    finally:
        if sock is not None:
            sock.close()

# elsewhere...
HOST = 'localhost'
PORT = 27017
throw_if_mongodb_is_unavailable(HOST, PORT)
import pymongo
conn = pymongo.MongoClient(HOST, PORT)
print(conn.admin.command('ismaster'))
# etc.

有很多问题无法解决,但如果服务器无法运行或无法访问,则会立即向您显示。

答案 3 :(得分:0)

<强> serverSelectionTimeoutMS

  

这定义了在抛出之前阻止服务器选择的时间   例外。默认值为30,000(毫秒)。肯定是   可在客户端级别配置。它绝对不能配置   数据库对象,集合对象的级别,或者在级别上   个人查询。

     

选择此默认值足以支持典型服务器   初选完成。随着服务器提高速度   选举,这个数字可能会向下修改。

     

可以容忍服务器选择长时间延迟的用户   拓扑结构的变化可以将其设置得更高。想要&#34;失败的用户   快速&#34;当拓扑结构处于不稳定状态时,可以将其设置为较小的数字。

     

serverSelectionTimeoutMS为零可能在某些方面具有特殊含义   驱动程序;此规范中未定义零的含义,而是所有驱动程序   应该记录零的含义。

https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst#serverselectiontimeoutms

# pymongo 3.5.1
from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError

client = MongoClient("mongodb://localhost:27000/", serverSelectionTimeoutMS=10, connectTimeoutMS=20000)

try:
    info = client.server_info() # Forces a call.
except ServerSelectionTimeoutError:
    print("server is down.")

# If connection create a new one with serverSelectionTimeoutMS=30000

答案 4 :(得分:0)

也可以这样检查:

from pymongo import MongoClient
from pymongo.errors import OperationFailure

def check_mongo_connection(client_uri):
    connection = MongoClient(client_uri)

    try:
        connection.database_names()
        print('Data Base Connection Established........')

    except OperationFailure as err:
        print(f"Data Base Connection failed. Error: {err}")

check_mongo_connection(client_uri)