7

我正在使用 grequests python 库将 GET 请求异步发送到我们的服务器。

我不知道如何获取正在发送的请求池中每个单独请求的服务器响应时间?

unsentrequests=(grequests.get(u) for u in self.urls) # make a pool of requests
responses=grequests.map(unsentrequests) # send the requests asynchronously

要获取请求-响应对的开始时间,我可以执行以下操作:

grequests.get(u,headers={'start':time.time())
print responses[0].request.headers['start_time']

但是我怎样才能掌握收到回复的时间呢?

4

1 回答 1

14

grequests,如requests,支持hook关键字参数,您可以在其中分配对响应对象执行某些操作的函数:

def do_something(response):
    print response.status_code

unsentrequests=(grequests.get(u, hooks = {'response' : do_something}) for u in self.urls) 
responses=grequests.map(unsentrequests)

我更喜欢requests直接在循环中使用gevent来获得更明确的代码:

import gevent.monkey
gevent.monkey.patch_socket()
from gevent.pool import Pool
import requests

def check_urls(urls):

    def fetch(url):
        response = requests.request('GET', url, timeout=5.0)
        print "Status: [%s] URL: %s" % (response.status_code, url)

    pool = Pool(20)
    for url in urls:
        pool.spawn(fetch, url)
    pool.join()
于 2013-01-10T13:47:46.780 回答