简体   繁体   English

在单个线程中使用阻塞HTTP库和Python并发http请求

[英]Concurrent http requests using a blocking http library with Python in a single thread

So I have this problem I am trying to solve in a particular way, but I am not sure how hard it is to achieve. 因此,我有一个要尝试以特定方式解决的问题,但是我不确定要实现多少困难。

I would like to use the asyncio/coroutines features of Python 3.4 to trigger many concurrent http requests using a blocking http library, like requests, or any Python api that does http requests like boto for aws. 我想使用Python 3.4的asyncio / coroutines功能,使用阻塞的http库(例如请求)或执行HTTP请求(例如aws的boto)的任何Python api触发许多并发的HTTP请求。

I know about run_in_executor() method to run tasks in threads/processes, but I would like to avoid that. 我知道在线程/进程中运行任务的run_in_executor()方法,但是我想避免这种情况。

I would like to do it in a single-thread, using those select features in Linux/Unix kernel. 我想在单线程中使用Linux / Unix内核中的那些选择功能来实现。

Actually I was following David Beazley's presentation on this, and I was trying to use this code: https://github.com/dabeaz/concurrencylive/blob/master/aserver.py 实际上,我正在关注David Beazley对此的介绍,并且正在尝试使用以下代码: https : //github.com/dabeaz/concurrencylive/blob/master/aserver.py

but without the future/pool stuff, and use my blocking-api call instead of computing the Fibonacci number. 但没有Future / Pool内容,请使用我的Blocking-api调用代替计算斐波那契数。

Put it seems that the http requests are still running in sequence. 简而言之,http请求似乎仍在按顺序运行。

Any ideas if this is possible? 有什么想法可能吗? And how? 如何?

Thanks 谢谢

Not possible. 不可能。 All the calls that the requests library makes to the underlying socket are blocking (ie socket.read ) because the socket is in blocking mode. 由于套接字处于阻塞模式,因此requests库对基础套接字的所有调用都处于阻塞状态(即socket.read )。 You could put the socket into non-blocking mode, but then socket.read would fail. 您可以将套接字置于非阻塞模式,但随后socket.read将失败。 You basically need an event-loop to tell you when it's possible to do a socket.read , but blocking libraries aren't written with one in mind. 基本上,您需要一个事件循环来告诉您何时可以进行socket.read ,但是编写阻塞库并不是一个人在意的。 This is the whole reason why asyncio exists; 这就是asyncio存在的全部原因。 providing a default event-loop that different libraries can share and make use of non-blocking file descriptors (eg sockets). 提供不同库可以共享并利用非阻塞文件描述符(例如套接字)的默认事件循环。

Use aiohttp , it's just as easy as requests and in the process you get to learn more about asyncio . 使用aiohttp ,它和requests一样简单 ,在此过程中,您将了解有关asyncio更多信息。 asyncio and the new Python 3.5 async/await syntax are the Future of networking IO; asyncio和新的Python 3.5 async/await语法是网络IO的未来; yield to it (pun intended). 屈服(双关语意)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM