2016-07-25 10 views
1

私は非同期要求を送信するためにhttpclient.HTTPRequestライブラリを使用していますが、要求間に遅延を追加する必要があります。 これは、RPS(Requests per second)= 5を設定することを意味します。各要求応答を待たずに要求を非同期的に送信するにはどうすればよいですか。遅延を伴うHTTPクライアント非同期呼び出し

これは私のコードです:

def process_campaign(self, campaign_instance): 
    ioloop.IOLoop.current().run_sync(lambda: start_campaign(campaign_instance)) 

@gen.coroutine 
def start_campaign(campaign_instance): 
     ... 
     while True: 
      try: 
       log.info("start_campaign() Requests in Queue: {}".format(len(web_requests))) 
       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_url, 
               body=json.dumps(web_request), 
               headers=headers, 
               request_timeout=15, 
               method="POST") 
       response = yield http_client.fetch(request) 

      except httpclient.HTTPError, e: 
       log.exception("start_campaign() " + str(e)) 

      except IndexError: 
       log.info('start_campaign() Campaign web requests completed. Errors {}'.format(api_errors)) 
       break 

しかし、先に進む前に、HTTPの応答を待つように思われます。

答えて

0

あなたは試すことができます:

class WebRequest(RequestHandler): 
    def __init__(self, web_request): 
     self.delay = 0 
     self.web_request = web_request 

    @asynchronous 
    def post(self): 
     IOLoop.instance().add_timeout(self.delay, self._process) 

    @gen.coroutine 
    def _process(self): 
     try: 
      http_client = httpclient.AsyncHTTPClient() 
      log.info("start_campaign() Web request: {}".format(self.web_request)) 
      headers = {'Content-Type': 'application/json'} 
      request = httpclient.HTTPRequest(auth_username=settings.api_account, 
              auth_password=settings.api_password, 
              url=settings.api_url, 
              body=json.dumps(self.web_request), 
              headers=headers, 
              request_timeout=15, 
              method="POST") 
      response = yield http_client.fetch(request) 
     except Exception, exception: 
      log.exception(exception) 

あなたのwhileループを再使用します。この新しい方法で私のエラーを処理する方法

while True: 
      try: 
       web_request = web_requests.pop() 
       time.sleep(delay) 
       client = WebRequest(web_request) 
       client.post() 

      except IndexError:    
       break 
+0

を? – californian

関連する問題