装饰您的方法,
gen.coroutine并产生一个期货列表。这是一个简单的例子:
from tornado import gen, web, httpclientclass StreamingHandler(web.RequestHandler): @web.asynchronous @gen.coroutine def get(self): client = httpclient.AsyncHTTPClient() self.write('some opening') self.flush() requests = [ httpclient.HTTPRequest( url='http://httpbin.org/delay/' + str(delay), streaming_callback=self.on_chunk ) for delay in [5, 4, 3, 2, 1] ] # `map()` doesn't return a list in Python 3 yield list(map(client.fetch, requests)) self.write('some closing') self.finish() def on_chunk(self, chunk): self.write('some chunk') self.flush()
请注意,即使请求是“向后”产生的,第一个块仍将在大约一秒钟后收到。如果您同步发送它们,则需要15秒。当您异步请求它们时,只需花费5。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)