【问题标题】:asynchronous HTTP POST requests in PythonPython 中的异步 HTTP POST 请求
【发布时间】:2021-08-23 15:18:05
【问题描述】:

我有一个代码,它为列表中的所有元组按顺序发布 HTTP 请求,并将响应附加到另一个列表。

import requests

url = 'https://www....'
input_list = [(1,2),(6,4),(7,8)]
output_list = []

for i in input_list:
   resp = (requests.post('url',data = i[1]).text,i[0])
   output_list.append(resp)

print(output_list)

有人可以帮助我指导并行发出 HTTP 请求吗?

【问题讨论】:

  • 你可以通过两种方式来完成,或者使用多处理(一次全部)或异步(一个一个,但在执行时重叠),你必须首先决定什么是最耗时的部分,是你发出请求后必须等待很多,然后我可以帮你写一个异步编程的解决方案或者整个循环的处理花费最多的时间,然后我可以帮助你进行多处理,但首先你有决定哪种并发方法可以为您的问题提供最佳解决方案。
  • @SAK,我会说没有很长的等待时间。所以异步编程很适合我的问题。
  • 如果发送请求后没有等待时间,那么异步编程实际上会使其变慢,例如,如果您发出请求并且需要 500 毫秒才能获得响应,然后系统等待response 它将在循环中执行下一次迭代,而不是如果它只需要 5ms 即可完成,那么 async 实际上会增加更多开销并使其变慢。
  • @SAK,每个请求大约需要 60 毫秒。您认为哪种方法有效?
  • 60ms 实际上对于多处理来说是更少的方式并且不适合异步,但是如果你真的想在这种情况下节省时间,它会设置一个多处理池执行器,这是最简单和在 python 中做的标准方法。我会在短时间内发布多处理解决方案的答案。

标签: python python-3.x async-await python-asyncio aiohttp


【解决方案1】:

由于requests 库本身不支持异步,我会使用multiprocessing.pool.ThreadPool,假设大部分时间都花在等待 IO 上。否则使用multiprocessing.Pool 可能会有好处

from multiprocessing.pool import ThreadPool
import requests

url = 'https://www....'
input_list = [(1,2),(6,4),(7,8)]

def get_url(i):
  return (requests.post('url',data = i[1]).text,i[0])

with ThreadPool(10) as pool: #ten requests to run in paralel
  output_list = list(pool.map(get_url, input_list))

【讨论】:

    猜你喜欢
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多