Python:无法建立连接,因为目标计算机主动拒绝它

时间:2017-01-17 06:33:54

标签: python multithreading python-2.7 python-multithreading urlopen

我有一个多线程python程序,它会不断打开与本地URL( http://testing.com/sendMessages_mock.php )的连接,我已经安装了WAMP并在本地安装了sendMessages_mock.php文件进行测试目的。有时,我得到" [Errno 10061]无法建立连接,因为目标计算机主动拒绝它"

每个线程都会调用此函数。每一秒,就会有数百个线程调用此函数。仅针对少数线程调用获取此异常。有什么想法吗?

def sendMessage(body):
    try:
        request = Request(url="http://testing.com/sendMessages_mock.php", data=json.dumps(body))
        request.add_header('Authorization', 'key=' + CONST.API_KEY)
        request.add_header('Content-Type', 'application/json')
        response = urlopen(request)
        responseData = response.read().decode('utf-8')

    except Exception as exceptionErr:
        print("Oops! " + str(traceback.format_exc()))

1 个答案:

答案 0 :(得分:1)

如果每秒过多的调用是导致WAMP拒绝请求的问题,并且您想在Python端解决此问题,则可以编写限制器类来处理sendMessage执行并限制调用次数。

请注意,这是我对别人问题的第一个回答,所以这可能是绝对错误的。请有合理的怀疑态度。

#python 2.7
import threading

class Throttle(object):
    def __init__(self, call_limit, interval):
        self.call_limit = call_limit
        self.interval = interval
        self.cleaner = None
        self.buffer = threading.Semaphore(call_limit)
        self.calls_in_buffer = 0

    def call(self, function, *args):
        self.buffer.acquire()

        self.calls_in_buffer += 1
        try:
            return function(*args)
        except:
            raise
        finally:
            if self.cleaner == None:
                self._init_cleaner()

    def _drain(self):
        for i in range(self.call_limit):
            self.calls_in_buffer -= 1
            self.buffer.release()
        self.cleaner = None

    def _init_cleaner(self):
        self.cleaner = threading.Timer(self.interval, self._drain)
        self.cleaner.daemon = True
        self.cleaner.start()

通过这样的类进行调用可以有效地限制请求,因此服务器将能够处理它们。