V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
aiqier
V2EX  ›  Python

tornado 在同时发出 n 个请求时,如何让其中 1 个有结果就返回?

  •  
  •   aiqier · 2016-10-19 22:10:58 +08:00 · 2217 次点击
    这是一个创建于 2750 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我知道 tornado 可以用如下方式,同时并发 n 个请求:

    response1, response2,... responsen = yield [http_client.fetch(url1) , http_client.fetch(url2), ...... ,http_client.fetch(url2) ]

    等到 n 个请求都响应了之后,会返回给程序控制权,那么我的问题是:

    1.如果我想其中一个有结果了,就返回 yield 继续执行,应该怎么实现?

    2.如果我要让其中 i 个请求有结果了就返回呢?

    5 条回复    2016-10-29 21:38:43 +08:00
    sivacohan
        1
    sivacohan  
       2016-10-20 00:00:59 +08:00 via iPad
    你是方法 A 说发出 n 个请求,当 i 个请求返回时( i 小于等于 n )。放弃其余请求,方法 A 返回。

    这种情况下你可以注册多个 handler 扔到 ioloop 里,然后搞个计数器。
    或者使用 threading ,然后循环坚持每个线程有没有返回。

    第一种复杂点,第二种代码少,但实际上是错的, for 循环会阻塞。
    husinhu
        2
    husinhu  
       2016-10-20 11:17:33 +08:00
    yieldpoints.waitany()
    NxnXgpuPSfsIT
        4
    NxnXgpuPSfsIT  
       2016-10-28 23:09:33 +08:00
    aiqier
        5
    aiqier  
    OP
       2016-10-29 21:38:43 +08:00
    @NxnXgpuPSfsIT 这两个帖子都是我发的,为了能更好的收集到问题,谢啦。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1837 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:39 · PVG 08:39 · LAX 17:39 · JFK 20:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.