立即处理异步响应

Handling async responses immediately

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

我找到了一些异步示例,但它们都展示了在解析完所有 link 之后如何处理结果,而我需要在收到后立即解析它,类似这样,但这段代码没有没有任何速度改进:

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())

我放弃了使用异步,线程解决了我的问题,多亏了这个答案

from threading import Thread
import requests
import time
class myClassA(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()
    def run(self):
        while True:
            r = requests.get('https://ex.com')
            print(r.status_code, time.time())
for i in range(5):
    myClassA()

but this code doesn't give any speed improvement

asyncio(和一般的 async/concurrency)为 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.Cliensession() as session: 必须高于(外部)while True: 才能正常工作。实际上,无论如何,为您的所有请求设置一个 ClientSession() 是一个很好的做法。