V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Tornado Documentation
http://www.v2ex.com/tornado/
Tornado on GitHub
https://github.com/facebook/tornado/
Tornado Gists
http://tornadogists.org/
aiqier
V2EX  ›  Tornado

tornado 并行异步,如何保证在只有部分请求成功后,结果依旧可用。

  •  
  •   aiqier · 2016-06-30 22:46:47 +08:00 · 8638 次点击
    这是一个创建于 2827 天前的主题,其中的信息可能已经有所发展或是发生改变。

    tornado 可以使用如下方式并行异步请求。

    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response1, response2 = yield [http_client.fetch(url1),
                                      http_client.fetch(url2)]
    

    这个时候, 1,2 是同时发送出去的,也就是说使用这种方式,可以让 n 个请求,同时发出去,等他们都返回了再统一返回。

    那么我要如何保证,其中一个请求坏了,其余的结果依旧可用?

    3 条回复    2016-07-01 13:43:15 +08:00
    gulu
        1
    gulu  
       2016-07-01 10:51:57 +08:00 via Android
    你把右边的函数改一下,做一个 `try ... except ...`,保证无论如何函数都有返回。
    kinghui
        2
    kinghui  
       2016-07-01 13:40:52 +08:00   ❤️ 1
    加个 wrapper 包装一下:
    ```
    @gen.croutine
    def _proxy(method, *args, **kwargs):
    try:
    ret = yield method(*args, **kwargs)
    except ErrorYourWantCatch:
    # logging or something else
    ret = None
    raise gen.Return(ret)


    @gen.coroutine
    def get(self):
    http_client = AsyncHTTPClient()
    response1, response2 = yield [_proxy( http_client.fetch, url1),
    _proxy( http_client.fetch, url2)]
    ```
    kinghui
        3
    kinghui  
       2016-07-01 13:43:15 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4337 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 10:11 · PVG 18:11 · LAX 03:11 · JFK 06:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.