Python多线程和HTTP请求

时间:2012-05-16 22:11:19

标签: python multithreading http

我正在开发一个Python后端Web服务器,它可以从付费的第三方API中获取实时数据。 我需要非常快速地查询此API(每10秒约150个查询)。因此,我创建了一个小概念证明,它产生200个线程并将URL写入队列。然后,线程从队列中的url读取并发送HTTP请求。第三方API返回一个名为delay的值,即服务器处理请求所需的时间。 这是POC代码,只下载所有网址(不重复)。

_http_pool = urllib3.PoolManager()

def getPooledResponse(url):
    return _http_pool.request("GET", url, timeout=30)

class POC:
    _worker_threads = []
    WORKER_THREAD_COUNT = 200
    q = Queue.Queue()

    @staticmethod
    def worker():
        while True:
            url = POC.q.get()
            t0 = datetime.datetime.now()
            r = getPooledResponse(item)
            print "thread %s took %d seconds to process the url (service delay %d)" % (threading.currentThread().ident, (datetime.datetime.now() - t0).seconds, getDelayFromResponse(r))
            POC.q.task_done()

    @staticmethod
    def run():
          # start the threads if we have less than the desired amount
          if len(POC._worker_threads) < POC.WORKER_THREAD_COUNT:
              for i in range(POC.WORKER_THREAD_COUNT - len(POC._worker_threads)):
                  t = threading.Thread(target=POC.worker)
                  t.daemon = True
                  t.start()
                  POC._worker_threads.append(t)

          # put the urls in the queue
          for url in urls:
              POC.q.put(url)
              # sleep for just a bit so that the requests don't get sent out together (this is a limitation of the API I am using)
              time.sleep(0.3)   
POC.run()

当我运行此命令时,会以合理的延迟返回前几个结果:

thread 140544300453053 took 2 seconds to process the url (service delay 1.782)

然而,在大约10-20秒后,我得到了这些东西:

thread 140548049958656 took 23 seconds to process the url (service delay 1.754)

换句话说,即使服务器以较小的延迟返回,我的线程也需要更长的时间才能完成......

如何测试其他21个运行秒数的位置?

谢谢!

1 个答案:

答案 0 :(得分:0)

您应该在代码上使用profiler