你如何理解龙卷风中的ioloop

你如何理解龙卷风中的ioloop

本文介绍了你如何理解龙卷风中的ioloop?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来理解龙卷风中的ioloop,因为我看了好几遍官方文档,还是看不懂.具体来说,它为什么存在.

I am looking for a way to understand ioloop in tornado, since I read the official doc several times, but can't understand it. Specifically, why it exists.

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() 返回该线程的当前 io 循环.

I know what is IO, input and output, e.g. read a hard drive, display graph on the screen, get keyboard input.by definition, IOLoop.current() returns the current io loop of this thread.

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

There are many IO device on my laptop running this python code. Which IO does this IOLoop.current() return? I never heard of IO loop in javascript nodejs.

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

Furthermore, why do I care this low level thing if I just want to do a database query, read a file?

推荐答案

与其说是IOLoop,不如说是EventLoop,这样你就更清楚了.

Rather to say it is IOLoop, maybe EventLoop is clearer for you to understand.

IOLoop.current() 并没有真正返回一个 IO 设备,而只是一个纯 python 事件循环,它与 asyncio.get_event_loop()nodejs 中的底层事件循环.

IOLoop.current() doesn't really return an IO device but just a pure python event loop which is basically the same as asyncio.get_event_loop() or the underlying event loop in nodejs.

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

The reason why you need event loop to just do a database query is that you are using event-driven structure to do databse query(In your example, you are doing http request).

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

Most of time you do not need to care about this low level structure. Instead you just need to use async&await keywords.

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

Let's say there is a lib which supports asynchronous database access:

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

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

Then you just need to use this function in your handler:

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)

这篇关于你如何理解龙卷风中的ioloop?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:20