你怎么理解tornado中的ioloop?

How do you understand the ioloop in tornado?

我正在寻找一种方法来理解ioloop in tornado,因为我阅读了几次官方文档,但无法理解。具体来说,它为什么存在。

from tornado.concurrent import Future
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop
def async_fetch_future():
    http_client = AsyncHTTPClient()
    future = Future()
    fetch_future = http_client.fetch(
        "http://mock.kite.com/text")
    fetch_future.add_done_callback(
        lambda f: future.set_result(f.result()))
    return future

response = IOLoop.current().run_sync(async_fetch_future) 
# why get current IO of this thread? display IO, hard drive IO, or network IO? 
print response.body

我知道什么是IO,输入和输出,例如读取硬盘、在屏幕上显示图形、获取键盘输入。 根据定义,IOLoop.current() return 是该线程的当前 io 循环。

我的笔记本电脑上有很多 IO 设备 运行 这个 python 代码。这个IOLoop.current()return是哪个IO?我从未听说过 javascript nodejs 中的 IO 循环。

此外,如果我只是想做一个数据库查询,读取一个文件,为什么我要关心这个低级的东西?

与其说是IOLoop,或许EventLoop更容易让你理解。

IOLoop.current() 并不是真正的 return IO 设备,而只是一个纯粹的 python 事件循环,它与 asyncio.get_event_loop() 或底层事件循环基本相同nodejs.

之所以需要事件循环来执行数据库查询,是因为您正在使用事件驱动结构来执行数据库查询(在您的示例中,您正在执行 http 请求)。

大多数时候你不需要关心这个底层结构。相反,您只需要使用 async&await 个关键字。

假设有一个支持异步数据库访问的库:

async def get_user(user_id):
    user = await async_cursor.execute("select * from user where user_id = %s" % user_id)
    return user

那么你只需要在你的处理程序中使用这个函数:

class YourHandler(tornado.web.RequestHandler):

    async def get():
        user = await get_user(self.get_cookie("user_id"))
        if user is None:
            return self.finish("No such user")
        return self.finish("Your are %s" % user.user_name)

I never heard of IO loop in javascript nodejs.

在node.js中,等价的概念是event loop。节点事件循环大部分是不可见的,因为所有程序都使用它 - 它是回调之间的 运行ning。

在Python中,大多数程序不使用事件循环,因此当您需要时,您必须自己运行。这可以是 Tornado IOLoop、Twisted Reactor 或 asyncio 事件循环(所有这些都是特定类型的事件循环)。

Tornado 的 IOLoop 的命名可能令人困惑 - 它不直接执行任何 IO。相反,它协调程序中可能发生的所有不同的 IO(主要是网络 IO)。将其视为 "event loop" 或 "callback runner" 可能会有所帮助。