how to use Asynchttp in tornado

一世执手 提交于 2019-12-13 18:43:46

问题


AsynceHTTPClient isn't a non-blocking client?

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

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

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

but the real result is

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

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 mode is there something wrong with my code? what should i do?


回答1:


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.

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

As the documentation says:

If you need to get the result of each future as soon as possible, or if you need the result of some futures even if others produce errors, you can use WaitIterator.

It fits your use case perfectly.

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

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)

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.




回答2:


200 is your status code. It's going like

go--- r.status_code b'' go--- r.status_code b'' .......

When you remove your status code from the print is should be printing

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



来源:https://stackoverflow.com/questions/54124609/how-to-use-asynchttp-in-tornado

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!