推荐学习书目
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
whx20202
V2EX  ›  Python

tornado 里面如果用 Requests 或者其他 httpSDK,那么如何非阻塞编程呢?

  •  
  •   whx20202 · Jan 3, 2019 · 2736 views
    This topic created in 2697 days ago, the information mentioned may be changed or developed.

    我知道 tornado 有 AsyncHttpClient,用它 + callback 肯定没错。

    但是有的时候我用的可能是 SDK,比如 SDK 访问一个 API,一次 http 请求对面要 2 秒才能响应。

    那么如果是 gevent,我理解他有猴子补丁,可以在我网络阻塞的时候,切到别的任务上工作,等到网络连接结束的时候,再切回来。

    我的问题是:

    1. tornado 是不是 不能在我使用基于 Http 的 SDK,或者 Requests 库的时候,自动识别我网络请求阻塞了,然后处理别的任务?

    2. 如果在 tornado 下不使用 AsyncHttpClient,达到我的目的呢?

    搜了一圈谷歌,全是给我讲 io 多路复用和信号驱动,很少有提到这块相关的

    6 replies    2019-01-04 00:25:22 +08:00
    locoz
        1
    locoz  
       Jan 3, 2019   ❤️ 1
    用异步的 HTTPClient 库就可以了,比如 aiohttp。
    如果你用的那个 SDK 本身没有用异步的库,那么你要么把他重写成异步的,要么用类似 asyncio.run_in_executor 的方式去运行。
    janxin
        2
    janxin  
       Jan 3, 2019
    不能自动把同步变成异步处理请求,除非是 gevent 那种猴子布丁。用 asyncio.run_in_executor 是新起线程去执行
    whx20202
        3
    whx20202  
    OP
       Jan 3, 2019
    @janxin #2 asyncio.run_in_executor 好的好的,我研究一下。
    zhengxiaowai
        4
    zhengxiaowai  
       Jan 3, 2019   ❤️ 1
    whx20202
        5
    whx20202  
    OP
       Jan 3, 2019
    @zhengxiaowai #4 感谢,对我来说明显第二种合适。

    > 使用 gen.coroutine 装饰器编写异步函数,如果库本身不支持异步,那么响应任然是阻塞的。

    第二种方法,ThreadPoolExecutor,起了一个另外的线程去做事情,能满足我的需求。
    之前一直不敢用的原因是,不清楚这种方法,到底是不是在主线程里做的,如果是的那肯定不敢用了么。
    现在看了这篇文章,大致明白了。
    conn4575
        6
    conn4575  
       Jan 4, 2019 via Android
    尽量找支持 asyncio 的 sdk,使用 ThreadPoolExecutor 太多的话会主线程的轮循效率
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2832 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 466ea39e · 38ms · UTC 06:02 · PVG 14:02 · LAX 23:02 · JFK 02:02
    ♥ Do have faith in what you're doing.