如何在 PyMongo 中检查连接是否仍然存在?有什么优雅的方法可以做到这一点,或者只是尝试一个简单的查询和解析器结果?
请您参考如下方法:
我不认为有一种优雅的方式。 Pymongo 有 AutoReconnect如果先前建立的连接丢失,将抛出异常。您应该捕获此异常并重试将导致重新建立连接的操作。
我发现处理 AutoReconnects 的一种相对轻松的方法是将 DB 操作隔离在单独的方法中,并用类似这样的装饰器包装它们:
from pymongo.errors import AutoReconnect
def autoreconnect_retry(fn, retries=3):
def db_op_wrapper(*args, **kwargs):
tries = 0
while tries < retries:
try:
return fn(*args, **kwargs)
except AutoReconnect:
tries += 1
raise Exception("No luck even after %d retries" % retries)
return db_op_wrapper
用法:
@autoreconnect_retry
def insert_foo_record(foo):
# Perform db operation
pass
@autoreconnect_retry(20)
def get_foo_record(id):
# Perform db operation
pass
