【发布时间】: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