grequests以哪种方式异步?

发布于 2021-01-29 15:10:58

我一直在使用python请求库一段时间,最近需要异步发出请求,这意味着我想发送HTTP请求,让我的主线程继续执行,并在请求退货。

自然地,我被带到了grequests库(https://github.com/kennethreitz/grequests),但是我对此行为感到困惑。例如:

import grequests

def print_res(res):
    from pprint import pprint
    pprint (vars(res))

req = grequests.get('http://www.codehenge.net/blog', hooks=dict(response=print_res))
res = grequests.map([req])

for i in range(10):
    print i

上面的代码将产生以下输出:

<...large HTTP response output...>

0
1
2
3
4
5
6
7
8
9

grequests.map()调用显然会阻塞,直到HTTP响应可用为止。似乎我在这里误解了“异步”行为,而grequests库仅用于同时执行多个HTTP请求并将所有响应发送到单个回调。这个准确吗?

关注者
0
被浏览
47
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    .map()是指并行运行多个URL的检索,并且确实会等待这些任务完成(gevent.joinall(jobs))被调用。

    使用.send(),而不是产卵的工作,使用Pool实例

    req = grequests.get('http://www.codehenge.net/blog', hooks=dict(response=print_res))
    job = grequests.send(req, grequests.Pool(1))
    
    for i in range(10):
        print i
    

    没有池,.send()调用将仍然阻塞,但仅针对gevent.spawn()执行的调用。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看