简体   繁体   English

Python:如何同时发送多个http请求? (如叉子)

[英]Python: How can i send multiple http requests at the same time? (like fork)

Let's say that i have a way to send http request to a server. 假设我有一种方法可以将HTTP请求发送到服务器。 How it's possible to send two of these requests (or more) to the server at the same time? 如何将其中两个(或多个)请求同时发送到服务器? For example maybe by fork a process? 例如,也许通过分叉过程? How can i do it? 我该怎么做? (also i'm using django) (我也在用django)

#This example is not tested...
import requests

def tester(request):
    server_url = 'http://localhost:9000/receive'

    payload = {
        'd_test2': '1234',
        'd_test2': 'demo',
        }
    json_payload = simplejson.dumps(payload)
    content_length = len(json_payload)

    headers = {'Content-Type': 'application/json', 'Content-Length': content_length}
    response = requests.post(server_url, data=json_payload, headers=headers, allow_redirects=True)

    if response.status_code == requests.codes.ok:
        print 'Headers: {}\nResponse: {}'.format(response.headers, response.text)

Thanks! 谢谢!

I think you want to use threads here rather than forking off new processes. 我认为您想在这里使用线程,而不是分叉新进程。 While threads are bad in some cases, that isn't true here. 尽管在某些情况下线程很糟糕,但在这里不是这样。 Also, I think you want to use concurrent.futures instead of using threads (or processes) directly. 另外,我认为您想使用concurrent.futures而不是直接使用线程(或进程)。

For example, let's say you have 10 URLs, and you're currently doing them one in a row, like this: 例如,假设您有10个URL,并且您当前正在连续执行这些操作,如下所示:

results = map(tester, urls)

But now, you want to send them 2 at a time. 但是现在,您想一次发送给他们2个。 Just change it to this: 只需将其更改为:

with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
    results = pool.map(tester, urls)

If you want to try 4 at a time instead of 2, just change the max_workers . 如果您想一次尝试4次而不是2次,则只需更改max_workers In fact, you should probably experiment with different values to see what works best for your program. 实际上,您可能应该尝试不同的值,以查看最适合您的程序的值。

If you want to do something a little fancier, see the documentation—the main ThreadPoolExecutor Example is almost exactly what you're looking for. 如果您想做些更简单的事情,请参阅文档-ThreadPoolExecutor示例几乎正是您所需要的。

Unfortunately, in 2.7, this module doesn't come with the standard library, so you will have to install the backport from PyPI. 不幸的是,在2.7,该模块没有配备标准库,所以你必须要安装的反向移植一封来自PyPI。

If you have pip installed, this should be as simple as: 如果您已经安装了pip ,则操作应该很简单:

pip install futures

… or maybe sudo pip install futures , on Unix. …或在Unix上sudo pip install futures

And if you don't have pip , go get it first (follow the link above). 如果您没有pip ,请先获取它(按照上面的链接)。


The main reason you sometimes want to use processes instead of threads is that you've got heavy CPU-bound computation, and you want to take advantage of multiple CPU cores. 有时您想要使用进程而不是线程的主要原因是您有大量的CPU绑定计算,并且您想利用多个CPU内核。 In Python, threading can't effectively use up all your cores. 在Python中,线程无法有效地耗尽所有内核。 So, if the Task Manager/Activity Monitor/whatever shows that your program is using up 100% CPU on one core, while the others are all at 0%, processes are the answer. 因此,如果“任务管理器” /“活动监视器” /无论什么显示您的程序在一个内核上使用了100%的CPU,而其他内核都使用了0%,则进程就是答案。 With futures , all you have to do is change ThreadPoolExecutor to ProcessPoolExecutor . 对于futures ,您要做的就是将ThreadPoolExecutor更改为ProcessPoolExecutor


Meanwhile, sometimes you need more than just "give me a magic pool of workers to run my tasks". 同时,有时您不仅需要“给我一个神奇的工人来执行任务”。 Sometimes you want to run a handful of very long jobs instead of a bunch of little ones, or load-balance the jobs yourself, or pass data between jobs, or whatever. 有时,您想运行一些非常长的工作,而不是一堆小工作,或者自己对工作进行负载平衡,或者在工作之间传递数据,等等。 For that, you want to use multiprocessing or threading instead of futures . 为此,您想使用multiprocessingthreading而不是futures

Very rarely, even that is too high-level, and directly tell Python to create a new child process or thread. 很少,即使太高级了,也直接告诉Python创建一个新的子进程或线程。 For that, you go all the way down to os.fork (on Unix only) or thread . 为此,您可以一直使用os.fork (仅在Unix上)或thread

I would use gevent , which can launch these all in so-called green-threads: 我将使用gevent ,它可以在所谓的绿色线程中启动所有这些:

# This will make requests compatible
from gevent import monkey; monkey.patch_all()
import requests

# Make a pool of greenlets to make your requests
from gevent.pool import Pool
p = Pool(10)

urls = [..., ..., ...]
p.map(requests.get, urls)

Of course, this example submits get s, but pool is generalized to map inputs into any function, including, say, yours to make requests. 当然,该示例提交了get ,但是将pool概括为将输入映射到任何函数中,包括您提出的请求。 These greenlets will run as nearly as simultaneously as using fork but are much faster and much lighter-weight. 这些绿色小工具将与使用fork几乎同时运行,但速度更快且重量更轻。

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

相关问题 Python:我如何发送多个HTTP请求并接收响应? - Python: How can i send multiple HTTP requests and receive the response? 如何一次在python中发送异步http请求? - How do I send asynchronous http requests in python one at a time? Python:同时多个HTTP请求 - Python: Multiple HTTP requests at the same time 如何发送多个HTTP请求python - How to send multiple http requests python 如何使用 Python 发送多个 HTTP 请求 - How to send multiple HTTP requests using Python 如何从Python向同一个长期运行的AWS Lambda函数发出多个HTTP RequestResponse请求? - How can I make multiple HTTP RequestResponse requests to the same long running AWS Lambda function from Python? 如何在 Django 中同时处理多个请求? - How can I handle multiple requests at the same time in Django? 如何在 python 中同时接收/发送多条消息? (Python 多线程) - How can I recieve/send multiple messages at the same time in python? (Python Multithreading) 如何使用python请求在同一连接中发送多个post请求 - How to send multiple post requests in same connection using python requests Python请求无法使用相同的密钥发送多个标头 - Python requests can't send multiple headers with same key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM