【问题标题】:Async with requests, how to get speed benefit与请求异步,如何获得速度优势
【发布时间】:2020-04-03 16:58:19
【问题描述】:

对 Async 还很陌生,很抱歉现在能够非常准确地表达这个问题。

我尝试按照示例 (https://pythonprogramming.net/asyncio-basics-intermediate-python-tutorial/) 使用异步,希望从多个 requests.get() 中获得一些速度优势,而不是同步方式。

import asyncio
import time
import requests

async def get_text(url):
    print(f"Load {url}")
    data = requests.get(url).text
    await asyncio.sleep(0.0001)
    print(f"Finished loading {url}")
    return data

async def main(name):
    tasks = [loop.create_task(get_text(n)) for n in name]
    await asyncio.wait(tasks)
    return tasks

if __name__ == '__main__':
    url = ['https://www.nytimes.com', 'https://news.yahoo.com']
    s = time.perf_counter()
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(main(url))
    loop.close()
    e = time.perf_counter() - s
    print(f"Time takes: {e:0.2f}s")

但这显然与按顺序运行两个请求相同。你能指出我做错了什么以及如何正确地做以节省时间吗?我看到另一个使用 ThreadPoolExecutor 和 loop.run_in_executor() 的示例,但我不确定如何合并它。

最好的问候,

J

【问题讨论】:

  • requests.get 是一个同步调用。它根本不会从async 中受益,并且会阻塞整个事件循环。
  • 您需要使用run_in_executor 方法才能使请求不被阻塞

标签: python python-asyncio


【解决方案1】:

requests 进行同步 IO,所以每次调用 requests.get 都会阻塞整个事件循环。如果需要异步 IO,请使用其他库,例如 aiohttp

【讨论】:

    【解决方案2】:

    您可以在这里使用 Python 多处理实现并行性。 https://docs.python.org/3.7/library/multiprocessing.html 需要阅读一些内容,但本质上这允许您启动新的非阻塞进程,这些进程将并行运行,并行执行您的代码/功能。所以,当然,您可以进行并行请求调用。尝试将您的代码转换为使用多处理,在此过程中如果您需要帮助,我们很乐意提供帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 2021-03-28
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 2020-03-22
      相关资源
      最近更新 更多