Python PyMongo:延时2秒

Python PyMongo:延时2秒,python,python-3.x,pymongo,Python,Python 3.x,Pymongo,我想在python中创建一个函数,在从MongoDB读取记录之前,应等待2秒,然后执行find query,如果记录不存在,则应在2秒后进行额外的读取重试。 如果记录不存在,则返回none 创建了如下函数: def get_document(self, count): count += 1 time.sleep(2) document = list(self.collection.find({"id": 1})) if document:

我想在python中创建一个函数,在从MongoDB读取记录之前,应等待2秒,然后执行find query,如果记录不存在,则应在2秒后进行额外的读取重试。 如果记录不存在,则返回none

创建了如下函数:

def get_document(self, count):
    count += 1
    time.sleep(2)
    document = list(self.collection.find({"id": 1}))
    if document:
        return document[0]
    else:
        return None if count == 2 else self.get_document(count)
我认为应该有更好的方法来做到这一点,那么什么是最好的pythonic方法来完成上述任务呢?

我认为我应该:

def get_document(self):
    for i in range(2):
        time.sleep(2)
        document = self.collection.find_one({"id": 1})

        if document is not None:
            return document

    return None
你不需要计数,只需要使用一个范围。如果只需要查找一个文档,则不需要使用
find()
,使用
find\u one()
可以简化索引列表等操作