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

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

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)

最佳答案

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

https://stackoverflow.com/questions/30539183/

相关文章:

python - 让 Spark、Python 和 MongoDB 协同工作

python - 为什么 PyMongo 3 给出 ServerSelectionTimeoutEr

node.js - 未找到匹配项的 Mongoose 查询返回什么?

node.js - 具有一对多关系的 Mongoose 文档引用

linux - Errr 'mongo.js:L112 Error: couldn' t 连接到服务

node.js - 使用 2 个字段的 Mongoose 自定义验证

node.js - 为什么MongoDB Node Driver生成实例池被破坏错误?

mongodb - Mongoose 是否支持 Mongodb `findAndModify` 方法

mongodb - 在 MongoDB 中存储 ObjectId 及其字符串形式之间的区别

node.js - 使用 mongoose 在 mongodb 中设置集合的到期时间