gpt4 book ai didi

python - 立即处理异步响应

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:26 27 4
gpt4 key购买 nike

我需要反复解析一个链接内容。同步方式每秒给我 2-3 个响应,我需要更快(是的,我知道,太快也不好)

我找到了一些异步示例,但它们都显示了在解析所有链接后如何处理结果,而我需要在收到后立即解析它,就像这样,但这段代码没有提供任何速度改进:

import aiohttp
import asyncio
import time
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()

async def main():
while True:
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'https://example.com')
print(time.time())
#do_something_with_html(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

最佳答案

but this code doesn't give any speed improvement

asyncio(以及一般的异步/并发)提高了相互交错的 I/O 事物的速度。

当您所做的一切都是await something 并且您永远不会创建任何并行任务时(使用asyncio.create_task()asyncio.ensure_future() 等)那么你基本上就是在做经典的同步编程:)

那么,如何使请求更快:

import aiohttp
import asyncio
import time

async def fetch(session, url):
async with session.get(url) as response:
return await response.text()

async def check_link(session):
html = await fetch(session, 'https://example.com')
print(time.time())
#do_something_with_html(html)

async def main():
async with aiohttp.ClientSession() as session:
while True:
asyncio.create_task(check_link(session))
await asyncio.sleep(0.05)

asyncio.run(main())

注意:async with aiohttp.Clientsession() as session: 必须高于(外部)while True: 才能工作。实际上,无论如何,为所有请求使用一个 ClientSession() 是一个很好的做法。

关于python - 立即处理异步响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53999676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com