繁体   English   中英

在 python(无线程)中限制并发 http 请求的最佳方法?

[英]Best way to limit concurrent http requests in python (no threads)?

我有兴趣为异步 function 调用创建一个池(它们将是 HTTP 请求)但是我想在一个线程中完成所有事情。 这样做的原因是产生多个线程会浪费资源(线程什么都不做,只是等待响应)。

import asyncio
import aiohttp

import some_library as pool

POOL_LIMIT = 3

urls = ["example.com/28409078",
"example.com/31145880",
"example.com/54622752",
"example.com/48008963",
"example.com/82016326",
"example.com/75587921",
"example.com/2988065",
"example.com/47574087",
"example.com/13478021",
"example.com/46041669"]

def get(url):
  # return some promise here

# now perform the async operations
pool(limit=POOL_LIMIT, urls, get)


是否有可以为我管理异步池的 python 库? 在 Node.js 中,看起来有一个库可以做一些接近我想做的事情: https://github.com/rxaviers/async-pool

在这里,我使用基本的asyncio函数实现了一个池。

在职的:

  • 池以 maxsize 任务开始
  • 当第一个任务完成时,它将下一个任务添加到队列并打印其结果
  • 类似地,对于每个单独的任务完成,它会添加另一个任务直到 maxsize

代码:

import asyncio

async def pool(tasks, maxsize=3):
    pending = [tasks.pop(0) for _ in range(maxsize) if tasks]
    while pending:
        (done, pending) = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
        while True:
             if (not tasks) or (len(pending) >= maxsize):
                  break
             pending.add(tasks.pop(0))
        for task in done:
             print(task.result())
    print("POOL COMPLETED")

例如,您可以像这里一样创建任务和池:

async def work(index, sleep_time):
    await asyncio.sleep(sleep_time)
    return f"task {index} done"

tasks = [work(i, 1) for i in range(10)]

现在运行任务调用 asyncio.run

asyncio.run(pool(tasks, 3))

这只会并行运行 3 个任务

我不知道是否有一个流行的图书馆。 这是一种简单的方法:

async def get(url):
  # return some promise here

async def processQueue():
  while len(urls):
    url = urls.pop()
    await get(url)

async def main():
  await asyncio.gather(
    processQueue(),
    processQueue(),
    processQueue()
  )

asyncio.run(main())

你可能需要在 pop() 之前加一个锁,我不确定。

暂无
暂无

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

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