1

每当我启用 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 上。

谁能解释这种行为以及如何解决它?谢谢!

4

1 回答 1

2

看起来引发的异常与 HTTPretty 的猴子补丁套接字有关,每当我们调用不是 HTTP 请求的东西 时,settimeout(0)它都会调用自己的套接字(请参阅 参考资料)。这会将套接字置于非阻塞模式。套接字上的超时永远不会在 之后重置,因此后续调用失败并显示 (errno 10035)。这可能是 HTTPretty 中的一个错误。sendallreal_sendallreal_sendallrecvWSAEWOULDBLOCK

一种解决方法是在 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
于 2014-07-21T21:45:29.477 回答