龙卷风 AsyncHTTPClient 动态添加 http_client.fetch 到列表

tornado AsyncHTTPClient dynamic add http_client.fetch to list

这是代码

class GetdataHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        http_client = tornado.httpclient.AsyncHTTPClient()
        response1, response2, response3, response4, response5, response6, response7, response8, response9, response10 = yield [
        http_client.fetch('http://u.com/order/fa-huo?id=85223'),
        http_client.fetch('http://u.com/order/fa-huo?id=85224'),
        http_client.fetch('http://u.com/order/fa-huo?id=85225'),
        http_client.fetch('http://u.com/order/fa-huo?id=85226'),
        http_client.fetch('http://u.com/order/fa-huo?id=85227'),
        http_client.fetch('http://u.com/order/fa-huo?id=85228'),
        http_client.fetch('http://u.com/order/fa-huo?id=85229'),
        http_client.fetch('http://u.com/order/fa-huo?id=85230'),
        http_client.fetch('http://u.com/order/fa-huo?id=85231'),
        http_client.fetch('http://u.com/order/fa-huo?id=85232')]
        self.write('getData: %s  getData: %s  getData: %s  getData: %s  getData: %s  getData: %s  getData: %s  getData: %s  getData: %s  getData: %s'%(response1.body,response2.body,response3.body,response4.body,response5.body,response6.body,response7.body,response8.body,response9.body,response10.body))

        self.finish()

这是一种愚蠢的方式。 我将从 mysql.I 获取 ID 不知道我需要请求多少个 ID。 我不知道如何用 (for) 来做。 非常感谢任何建议。

使用简单的 `for,将需要额外的列表

ids = [111,222,333,444]
futures = []
for iid in ids:
    futures.append(http_client.fetch(url + iid)
responses = yield futures

# prepare output to user
bodies = []
for r in responses:
    bodies.append(r.body)

# join list of response bodies 
output = ' '.join(bodies) 
self.write(output)

或者您可以使用 list comprehension

class GetdataHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        http_client = tornado.httpclient.AsyncHTTPClient()
        url = 'http://u.com/order/fa-huo?id={}'

        ids = [111,222,333,444]  
        # from GET/POST params 
        # ids = self.get_arguments('ids')

        responses = yield [
            http_client.fetch(url.format(iid)) for iid in ids
        ]

        output = ' '.join(
            ['getData: {}'.format(r.body) for r in responses]
        )
        self.write(output)   
        self.finish()

但请注意,缺少错误处理。例如 - 如果 fetch 之一引发异常,您将得不到任何结果,您应该包装一些具有错误处理功能的函数(可能使用 raise_exception argument in fetch)。

更多信息: