Skip to main content
 首页 » 编程设计

python之Tornado Coroutine之自定义函数

2025年05月04日25mengfanrong

我正在理解 Tornado 的协程,所以让我们保持简单,粘贴的代码越多越好。

我想要的是让我自制的函数异步。

我可以在文档中找到的所有示例都属于相同的“隐藏”部分:AsyncHTTPClient。我不想进行 HTTP 调用。所以请不要给我那个类(class)的例子。我有兴趣从头开始创造一些东西。我在 Tornado coroutine 上尝试了所有可能性

目前我一直在测试 bash sleep 。这是代码:

import tornado.web 
import tornado.httpserver 
import tornado.gen 
import tornado.concurrent 
import subprocess 
import os 
 
@tornado.gen.coroutine 
def letswait(): 
    fut = tornado.concurrent.Future() 
    subprocess.check_output(["sleep", "5"]) 
    fut.set_result(42) 
    return fut 
 
class TestHandler1(tornado.web.RequestHandler): 
    @tornado.gen.coroutine 
    def get(self): 
        value = yield letswait() 
        self.render("test.html", num=value) 
 
class TestHandler2(tornado.web.RequestHandler): 
    def get(self): 
        self.render("test.html", num=66) 
 
class Application(tornado.web.Application): 
    def __init__(self): 
        DIRNAME = os.path.dirname(__file__) 
        STATIC_PATH = os.path.join(DIRNAME, '../static') 
        TEMPLATE_PATH = os.path.join(DIRNAME, '../template') 
        sets = { 
            "template_path":TEMPLATE_PATH, 
            "static_path":STATIC_PATH, 
            "debug":True, 
        } 
        tornado.web.Application.__init__(self, [ 
            (r"/test1", TestHandler1), 
            (r"/test2", TestHandler2), 
        ], **sets) 
 
def main(): 
    http_server = tornado.httpserver.HTTPServer(Application()) 
    http_server.listen(8888) 
    print "Let s start" 
    tornado.ioloop.IOLoop.instance().start() 
 
if __name__ == "__main__": 
    main() 

但是如果我访问 test1,那么我需要等待调用返回才能访问 test2。据我了解,我需要使用 gen.sleep(5)。但这只是一个例子。假设我没有在 bash 上运行 sleep 5,而是在某处运行 ssh 'do_something',这需要一些时间才能运行。

有人告诉我“这个函数不是异步的”。所以我的问题是如何使自定义函数异步?

编辑:稍微搜索后,我看到有 tornado.process https://gist.github.com/FZambia/5756470在这里使用。但是我的子流程来自第三方,所以我真的不能覆盖它。所以我的问题也是,如何将第 3 方库与该 gen.coroutine 系统集成?

解决方案:感谢下面的评论,我找到了解决方案:

import tornado.web 
import tornado.httpserver 
import tornado.gen 
import tornado.concurrent 
import subprocess 
import os 
 
from concurrent import futures 
 
# Create a threadpool, and this can be shared around different python files 
# which will not re-create 10 threadpools when we call it. 
# we can a handful of executors for running synchronous tasks 
 
# Create a 10 thread threadpool that we can use to call any synchronous/blocking functions 
executor = futures.ThreadPoolExecutor(10) 
 
def letswait(): 
    result_future = tornado.concurrent.Future() 
    subprocess.check_output(["sleep", "5"]) 
    result_future.set_result(42) 
    return result_future 
 
class TestHandler1(tornado.web.RequestHandler): 
    @tornado.gen.coroutine 
    def get(self): 
        value = yield executor.submit(letswait) 
        self.render("test.html", num=value) 
 
class TestHandler2(tornado.web.RequestHandler): 
    def get(self): 
        self.render("test.html", num=66) 
 
class Application(tornado.web.Application): 
    def __init__(self): 
        DIRNAME = os.path.dirname(__file__) 
        STATIC_PATH = os.path.join(DIRNAME, '../static') 
        TEMPLATE_PATH = os.path.join(DIRNAME, '../template') 
        sets = { 
            "template_path":TEMPLATE_PATH, 
            "static_path":STATIC_PATH, 
            "debug":True, 
        } 
        tornado.web.Application.__init__(self, [ 
            (r"/test1", TestHandler1), 
            (r"/test2", TestHandler2), 
        ], **sets) 
 
def main(): 
    http_server = tornado.httpserver.HTTPServer(Application()) 
    http_server.listen(8888) 
    print "Let s start" 
    tornado.ioloop.IOLoop.instance().start() 
 
if __name__ == "__main__": 
    main() 

请您参考如下方法:

我在这里问过类似的问题:Python Tornado - Confused how to convert a blocking function into a non-blocking function

问题是您的函数可能受 CPU 限制,唯一的方法是使用执行器。

from concurrent import futures 
 
# Create a threadpool, and this can be shared around different python files 
# which will not re-create 10 threadpools when we call it. 
# we can a handful of executors for running synchronous tasks 
 
# Create a 10 thread threadpool that we can use to call any synchronous/blocking functions 
executor = futures.ThreadPoolExecutor(10) 

然后你可以这样做:

@gen.coroutine 
def get(self): 
    json = yield executor.submit(some_long_running_function) 

这个任务将被搁置,独立运行,因为有一个 yield 关键字,tornado 会做一些其他的事情,同时在它当前运行的和你的进程之间做一个纯线程切换。这对我来说似乎工作正常。

换句话说,你可以将子进程包裹在执行器中,它会被异步处理。

如果你不想使用执行器,你的功能似乎需要以状态机的方式实现。

另一篇文章:https://emptysqua.re/blog/motor-internals-how-i-asynchronized-a-synchronous-library/

请注意,Momoko (Postgres) 和 Motor (MongoDB) 都是 I/O 绑定(bind)。

编辑: 我不确定 Tornado 有什么用。当我进行大量 I/O 时,我会使用 Tornado,因为我受 I/O 限制。但是,我想如果您的使用受 CPU 限制更多,您可能想看看 Flask。您可以轻松地使用 Gunicorn 和 Flask 创建简单的东西,并利用多核。尝试在 Tornado 中使用多线程或多核可能会给您带来很多麻烦,因为 Tornado 中的很多东西都不是线程安全的。

编辑 2:删除了 .result() 调用。