安装
grequests模块与工作
gevent(
requests不用于异步):
pip install grequests
然后将代码更改为如下所示:
import grequestsclass Test: def __init__(self): self.urls = [ 'http://www.example.com', 'http://www.google.com', 'http://www.yahoo.com', 'http://www.stackoverflow.com/', 'http://www.reddit.com/' ] def exception(self, request, exception): print "Problem: {}: {}".format(request.url, exception) def async(self): results = grequests.map((grequests.get(u) for u in self.urls), exception_handler=self.exception, size=5) print resultstest = Test()test.async()这是正式建议由
requests项目:
阻止还是不阻止?
使用默认的传输适配器后,请求将不提供任何类型的非阻塞IO。该
Response.content属性将阻塞,直到下载完整个响应。如果您需要更多的粒度,则库的流功能(请参阅流请求)允许您一次检索较小数量的响应。但是,这些调用仍将阻止。如果您担心阻塞IO的使用,那么有很多项目将Requests与Python的异步框架之一结合在一起。
grequests和都是两个很好的例子requests-futures。
使用这种方法让我用10个URL的noticable性能提升:
0.877sVS
3.852s与你原来的方法。



