tornado AsyncHTTPClient dynamic将http_client.fetch添加到列表中

时间:2017-01-06 09:49:54

标签: python mysql list tornado asynchttpclient

这是代码

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获取ID。我不知道我需要多少ID。 我不知道怎么做(for)。 非常感谢任何建议。

1 个答案:

答案 0 :(得分:0)

使用简单的`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)。

更多信息: