立即处理异步响应

时间:2019-01-01 23:15:09

标签: python python-3.x asynchronous python-asyncio aiohttp

我需要重复分析一个链接内容。同步方式每秒可以给我2-3个响应,我需要更快(是的,我知道,太快也很糟糕)

我找到了一些异步示例,但是所有示例都展示了解析所有链接后如何处理结果,而我需要在接收到后立即解析它,就像这样,但是这段代码并没有提高速度: / p>

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

2 个答案:

答案 0 :(得分:1)

  

但是这段代码并没有提高速度

异步(通常是异步/并发)可以提高相互交错的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()还是一个好习惯。

答案 1 :(得分:0)

由于这个答案,我放弃了使用异步,线程解决了我的问题 https://stackoverflow.com/a/23102874/5678457

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()
相关问题