本文介绍了如何在龙卷风中使用 Asynchttp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AsynceHTTPClient 不是非阻塞客户端吗?

AsynceHTTPClient isn't a non-blocking client?

当我使用请求获得响应时,它的工作.但是当我使用 AsyncTTTPClient 发布请求时,它不起作用.

when i use requests to get response,its work.but i when i use AsyncTTTPClient to post a request,its doesn't work.

async def go():
    print('go---------------')
    client = AsyncHTTPClient()
    request = HTTPRequest(url='http://127.0.0.1:8001/api',
method='GET',)
    r = await client.fetch(request)
    print(r.code, r.body)

async def m(r):
    for _ in range(r):
        await go()

loop = asyncio.get_event_loop()
loop.run_until_complete(m(100))

当我使用 AsyncHTTPClient 时,我认为结果就像这个内容

when i use AsyncHTTPClient i think the result is like this content

去---去---去---去---......

go--- go--- go--- go--- ......

但真正的结果是

go--- 200 b'' go--- 200 b'' ......

go--- 200 b'' go--- 200 b'' .......

我想要一个非阻塞请求,所以它可以先发送所有 100 个请求,然后再接收响应,但我在每次响应后都得到了每个响应.它不是非阻塞模式我的代码有问题吗?我该怎么办?

i want a non-blocking requests,so it may send all 100 requests first,and recive the response later, but i got the each response after each reponse .itsn't not-blocking modeis there something wrong with my code? what should i do?

推荐答案

您所看到的是在这种情况下使用协程的缺点.因为即使请求是非阻塞的,它们也不是真正的异步.

What you're seeing is a disadvantage of using coroutines in this case. Because even though the requests are non-blocking, they are not really asynchronous.

您可以使用 gen.Waiterator一次发送所有请求,真正异步.

You can use gen.WaitIterator to send all the requests at once, truly asynchronously.

正如文档所说:

如果你需要尽快得到每个future的结果,或者如果你需要一些future的结果即使其他一些产生错误,你可以使用WaitIterator.

它非常适合您的用例.

gen.WaitIterator 将任意数量的期货作为参数,并在期货完成时产生期货.

gen.WaitIterator takes an arbitrary number of futures as arguments and yields the futures as they finish.

但是,要使其工作,您需要将 for 循环移动到 go 协程内.示例:

However, for this to work, you;ll need to move your for loop inside the go coroutine. Example:

from tornado import gen

async def go(r):
    client = AsyncHTTPClient()
    futures = []

    for _ in range(r):
        print('go----------')
        request = HTTPRequest(url='http://127.0.0.1:8001/api', method='GET',)
        futures.append(client.fetch(request))

    async for result in gen.WaitIterator(*futures):
        print(result.code, result.body)

作为旁注,还有另一种方法可以实现这一点——使用回调.但是,WaitIterator 应该优先于回调.我写了一篇博客文章 关于这个,如果你有兴趣的话.


As a side note, there's another way to accomplish this—using callbacks. However, WaitIterator should be preferred over callbacks. I wrote a blog post about this sometime ago, if you're interested.

这篇关于如何在龙卷风中使用 Asynchttp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:20
查看更多