繁体   English   中英

httpretty.enable()之后MongoClient连接失败

[英]MongoClient ConnectionFailure after httpretty.enable()

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

我在Windows 8.1中使用Python 3.3。

谁能解释这种现象以及如何解决? 谢谢!

看起来正在引发的异常与HTTPretty的猴子修补套接字有关,每当我们在非HTTP请求中调用sendall时,该套接字都会在其自己的套接字上调用settimeout(0) (请参阅real_sendall )。 这会将套接字置于非阻塞模式。 real_sendall之后,套接字上的超时永远不会重置,因此后续对recv调用会因WSAEWOULDBLOCK (errno 10035)而失败。 这可能是HTTPretty中的错误。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM