2016-08-13 114 views
0

我试图以特定的速率发送API请求(使用QPS值的示例), 我使用以下代码启动我的请求(存储在web_requests列表中)。发送多个Web请求

如果我设置QPS = 10,延迟将是0.1s或100ms。我使用time.sleep(0.1)并发送一个请求,但是这个代码正在等待大约30ms的远端HTTP响应,所以我最终总共有0.3秒的额外延迟。 如何在不等待响应的情况下每秒发送X次Web请求?

@gen.coroutine 
def send_requests(campaign_instance): 
    ... 
    http_client = httpclient.AsyncHTTPClient() 
    while True: 
       try:       
        web_request = web_requests.pop() 
        time.sleep(delay) 
        headers = {'Content-Type': 'application/json'} 
        request = httpclient.HTTPRequest(auth_username=settings.api_account, 
                auth_password=settings.api_password, 
                url=settings.api_web_request, 
                body=json.dumps(web_request), 
                headers=headers, 
                request_timeout=5, 
                method="POST") 
        yield http_client.fetch(request, callback=partial(handle_response, web_request["to"])) 

        gen_log.info("start_campaign() Requests in Queue: {}".format(len(web_requests))) 

       except httpclient.HTTPError, exception: 
        gen_log.info.exception("start_campaign() ".format(exception)) 
        api_errors += 1 
        if handle_api_errors(api_errors): 
         break 
       except IndexError: 
        gen_log.info.info('start_campaign() Campaign web requests completed. API Errors: {}'.format(api_errors)) 
        break 

def start(): 
    ioloop.IOLoop.current().run_sync(lambda: send_requests(campaign_instance)) 
    log.info('process_campaign() Campaign completed') 
    campaign_instance.terminate() 

回答

1

只是不“屈服”未来由“取”返回。然后,您的协同程序将会立即继续循环,并在回读在后台完成时执行回调。

而且,永远不叫龙卷风应用“睡眠”:

http://www.tornadoweb.org/en/stable/faq.html#why-isn-t-this-example-with-time-sleep-running-in-parallel

如果你这样做,所有的处理停止,你的“取”挂直到睡眠完成。相反:

yield gen.sleep(delay) 
+0

工作后,你的意见。谢谢 – spicyramen