问题
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