httpretty.enable()之后的MongoClient ConnectionFailure

时间:2014-06-20 12:27:37

标签: python sockets pymongo httpretty

每当我启用HTTPretty时,我都无法与PyMongo建立连接。我知道HTTPretty会改变核心套接字模块;有没有办法解决这个问题?

代码示例:



    import pymongo
    import httpretty
    import time

    httpretty.enable()
    try:
        client = pymongo.MongoClient()
    except pymongo.errors.AutoReconnect:
        print("AutoReconnect")
        time.sleep(2)

引发异常:



    Traceback (most recent call last):
      File "C:\Python33\lib\site-packages\pymongo\mongo_client.py", line 363, in __init__
        self._ensure_connected(True)
      File "C:\Python33\lib\site-packages\pymongo\mongo_client.py", line 924, in _ensure_connected
        self.__ensure_member()
      File "C:\Python33\lib\site-packages\pymongo\mongo_client.py", line 797, in __ensure_member
        member, nodes = self.__find_node()
      File "C:\Python33\lib\site-packages\pymongo\mongo_client.py", line 888, in __find_node
        raise AutoReconnect(', '.join(errors))
    pymongo.errors.AutoReconnect: [WinError 10035] A non-blocking socket operation could not be completed immediately

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "tmp.py", line 7, in 
        client = pymongo.MongoClient()
      File "C:\Python33\lib\site-packages\pymongo\mongo_client.py", line 366, in __init__
        raise ConnectionFailure(str(e))
    pymongo.errors.ConnectionFailure: [WinError 10035] A non-blocking socket operation could not be completed immediately

我在使用Python 3.3的Windows 8.1上。

任何人都可以解释这种行为以及如何解决它吗?谢谢!

1 个答案:

答案 0 :(得分:2)

看起来引发的异常与HTTPretty的猴子补丁有关 套接字,只要我们在非HTTP请求的内容上调用settimeout(0),就会在自己的套接字上调用sendall(请参阅 real_sendall)。这个 将套接字置于非阻塞模式。套接字上的超时永远不会重置 在real_sendall之后,后来对recv的调用失败,WSAEWOULDBLOCK (错误10035)。这可能是HTTPretty中的一个错误。

一种解决方法是在之后重置套接字上的超时 real_sendall。这可以通过猴子修补来完成fakesocket.socket 在HTTPretty:

from httpretty.core import fakesock

class MySocket(fakesock.socket):
    def real_sendall(self, data, *args, **kw):
        super(MySocket, self).real_sendall(data, *args, **kw)
        # Restore non-zero timeout
        self.truesock.settimeout(self.timeout)

fakesock.socket = MySocket