我用requests-futures来异步抓取网页,而且我的机器有多核,所以我也想同时抓多个网站,然后我试着用concurrent.futures,看来concurrent.futures也提供异步方法,所以什么是concurrent.futures'async和request-futures'异步之间的区别?如果它们相同,意味着我可以反对请求 - 期货?python中concurrent.futures的async和requests-futures异步有什么区别?
1
A
回答
4
requests-futures
只是在concurrent.futures
之上的一个非常小的包装。您可以通过查看source code(为了简洁,删除文档字符串)看到这一点:
from concurrent.futures import ThreadPoolExecutor
from requests import Session
from requests.adapters import DEFAULT_POOLSIZE, HTTPAdapter
class FuturesSession(Session):
def __init__(self, executor=None, max_workers=2, *args, **kwargs):
super(FuturesSession, self).__init__(*args, **kwargs)
if executor is None:
executor = ThreadPoolExecutor(max_workers=max_workers)
# set connection pool size equal to max_workers if needed
if max_workers > DEFAULT_POOLSIZE:
adapter_kwargs = dict(pool_connections=max_workers,
pool_maxsize=max_workers)
self.mount('https://', HTTPAdapter(**adapter_kwargs))
self.mount('http://', HTTPAdapter(**adapter_kwargs))
self.executor = executor
def request(self, *args, **kwargs):
func = sup = super(FuturesSession, self).request
background_callback = kwargs.pop('background_callback', None)
if background_callback:
def wrap(*args_, **kwargs_):
resp = sup(*args_, **kwargs_)
background_callback(self, resp)
return resp
func = wrap
return self.executor.submit(func, *args, **kwargs) # This returns a concurrent.futures.Future
当您使用requests-futures
,你真的使用concurrent.futures.ThreadPoolExecutor
,它返回一个concurrent.futures.Future
当你submit
给它的任务。如果您更方便地使用requests-futures
提供的API来处理HTTP请求,可以坚持使用它,甚至可以使用由concurrent.futures
模块提供的其他方法返回的对象。
相关问题
- 1. 同步请求和异步请求之间有什么区别? (async = true/false)
- 2. 异步私有和私有异步的区别是什么?
- 3. pubsubhubbub - 同步和异步在订阅Feed时有什么区别?
- 4. python中的{}和[]有什么区别?
- 5. 非主线程中的async io和do io有什么区别?
- 6. Python中pycurl和curl有什么区别
- 7. python中b''和''有什么区别?
- 8. Python中!r和%r有什么区别?
- 9. active python和python有什么区别?
- 10. swift中的同步API和异步API之间有什么区别?
- 11. 异步调用和回调有什么区别
- 12. 聚合物异步和作业有什么区别
- 13. 只使用异步任务和任务有什么区别?
- 14. Python的__add__和__concat__有什么区别?
- 15. Python的ElementTree.XML()和ElementTree.fromstring有什么区别?
- 16. Python的pyautogui.PAUSE和time.sleep有什么区别?
- 17. 的Python:有什么区别 - ABS和operator.abs
- 18. 检查中同步检查和异步检查有什么区别?
- 19. 有什么区别`和$(Bash中有什么区别?
- 20. Python,Shapely:Polygon.contains和Polygon.within有什么区别?
- 21. Python 3.2和3.1有什么区别?
- 22. Django和Python有什么区别?
- 23. python mock和magic mock有什么区别?
- 24. django classonlymethod和python classmethod有什么区别?
- 25. opencv,python-opencv和libopencv有什么区别?
- 26. pytz和python-dateutil有什么区别?
- 27. Python:'is'和'=='有什么区别?
- 28. PyCUDA和NumbaPro CUDA Python有什么区别?
- 29. .NET double和python float有什么区别?
- 30. Python:__builtin__和__builtins__有什么区别?
Thx〜我也想利用多核心,所以concurrent.futures.ProcessPoolExecutor似乎更好? – leafonsword
@leafonsword那么,对于使用'requests'库,你可能可以使用'ThreadPoolExecutor'; HTTP请求是I/O绑定操作,这意味着GIL将在大部分时间被释放。如果你也试图同时执行CPU绑定操作,那么一定要使用'ProcessPoolExecutor'。 – dano