简体   繁体   English

tornado.web.RequestHandler.render_string()如何在不阻塞整个应用程序的情况下加载模板?

[英]How does tornado.web.RequestHandler.render_string() load a template without blocking the whole application?

I'm loading templates from a coroutine in Tornado using render_string() and it came to my mind that render_string() is not a coroutine. 我正在使用render_string()从Tornado中的协程加载模板,我想到render_string()不是协程。 So we're accessing the disk form a coroutine, but we're not yielding any futures. 因此我们从协同程序访问磁盘,但我们不会产生任何未来。 I wonder how does this work and if it blocks the application or not. 我想知道它是如何工作的,如果它阻止了应用程序。

It's true, the first time a given template is read from the disk, it blocks Tornado's event loop: 确实,第一次从磁盘读取给定模板时,它会阻止Tornado的事件循环:

class Loader(BaseLoader):
    def _create_template(self, name):
        path = os.path.join(self.root, name)
        with open(path, "rb") as f:
            template = Template(f.read(), name=name, loader=self)
            return template

This initial load is probably fast, since the template is likely only a few kilobytes and already loaded into the machine's in-memory filesystem cache. 这个初始加载可能很快,因为模板可能只有几千字节并且已经加载到机器的内存中文件系统缓存中。 Subsequent accesses of the same template by the same Tornado process are cached within Tornado itself: 通过相同的Tornado进程对同一模板的后续访问将在Tornado中自动缓存:

class BaseLoader(object):
    def load(self, name, parent_path=None):
        """Loads a template."""
        name = self.resolve_path(name, parent_path=parent_path)
        with self.lock:
            if name not in self.templates:
                self.templates[name] = self._create_template(name)
            return self.templates[name]

So it doesn't seem worthwhile for Tornado to defer the filesystem access to a thread. 因此,Tornado将文件系统访问权限推迟到线程似乎并不值得。

Often in Python async frameworks you'll see that not all I/O is performed asynchronously - quick and predictable blocking operations like accessing a file or a MySQL query might not block the loop long enough to worry about. 通常在Python异步框架中,您将看到并非所有I / O都是异步执行的 - 快速且可预测的阻塞操作(如访问文件或MySQL查询)可能无法长时间阻止循环而无法担心。 What's critical is that long or unpredictable operations, like calling a remote HTTP service, are scheduled on the event loop. 重要的是,在事件循环中调度长或不可预测的操作,如调用远程HTTP服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM