简体   繁体   English

Python:同时多个HTTP请求

[英]Python: Multiple HTTP requests at the same time

I am looking to set up an HTTP server which takes in some input and then the application needs to send multiple HTTP requests at the same time (to another server). 我希望建立一个HTTP服务器,该服务器接受一些输入,然后应用程序需要同时发送多个HTTP请求(到另一个服务器)。 What is the best approach for this? 最好的方法是什么?

If I use the Twisted framework, do I still need to use threading? 如果我使用Twisted框架,是否还需要使用线程?

You don't need to worry about threading or thread safety yourself. 您无需自己担心线程或线程安全。 Most of the time spent doing HTTP requests is waiting for a response, at which time Python can run other code in parallel safely. 执行HTTP请求的大部分时间都在等待响应,这时Python可以安全地并行运行其他代码。 Use some of the libraries and built-in functionality Python has to manage concurrent I/O waits. 使用某些库和内置功能Python必须管理并发I / O等待。

You could use gevent. 您可以使用gevent。 Twisted has similar functionality but may be more complex to learn to use. Twisted具有类似的功能,但学习起来可能更复杂。 There's also the multiprocessing.dummy functionality built-in to Python. Python还内置了multiprocessing.dummy功能。

If you go with something other than Twisted, you can and should use the requests library to do HTTP client stuff in conjunction with the above -- you may need to use grequests , which is a green-threaded variant, to do non-blocking I/O. 如果您使用的不是Twisted,则可以并且应该结合以上内容使用请求库来执行HTTP客户端操作-您可能需要使用grequests (这是绿色线程的变体)来执行非阻塞操作/ O。

If you use the Twisted networking engine, you do not need to use threading. 如果使用Twisted网络引擎,则无需使用线程。 Just issue the requests and wait for the responses by adding callbacks that will execute as they're available. 只需发出请求,然后通过添加将在可用时执行的回调来等待响应。

For a nice easy way to make HTTP requests using Twisted, you might want to consider Treq , a requests -inspired convenience layer for Twisted's HTTP client. 为了使用Twisted发出HTTP请求的一种简便方法,您可能需要考虑Treq ,这是Twisted HTTP客户端的受请求启发的便利层。

Either Threading or Twisted can do this. 穿线或扭曲均可做到这一点。

ie. 即。 If you use twisted, you won't need to use Threading. 如果使用双绞线,则无需使用线程。

Keep in mind that some servers have a limit on the number of connections they will allow from a single IP address. 请记住,某些服务器对单个IP地址允许的连接数量有限制。

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

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