Python Tornado协同程序-自定义函数
我正在理解Tornado中的协同程序,所以让我们保持一切简单,粘贴的代码越多越好 我想要的是使我自制的函数异步 我在文档中找到的所有示例都属于同一个“隐藏”部分:AsyncHTTPClient。我不想打HTTP电话。所以请不要给我举这个类的例子。我有兴趣从头开始创作。我已经试过了所有的可能性 现在我一直在用bash睡眠测试。代码如下:Python Tornado协同程序-自定义函数,python,asynchronous,tornado,Python,Asynchronous,Tornado,我正在理解Tornado中的协同程序,所以让我们保持一切简单,粘贴的代码越多越好 我想要的是使我自制的函数异步 我在文档中找到的所有示例都属于同一个“隐藏”部分:AsyncHTTPClient。我不想打HTTP电话。所以请不要给我举这个类的例子。我有兴趣从头开始创作。我已经试过了所有的可能性 现在我一直在用bash睡眠测试。代码如下: import tornado.web import tornado.httpserver import tornado.gen import tornado.co
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上运行sleep5
,而是在某处运行ssh“dou\u something”
,这需要一些时间来运行
我被告知“这个函数不是异步的”。所以我的问题是如何使自定义函数异步
编辑:在搜索了一点之后,我看到这里使用了tornado.process。但是我的子流程来自第三方,所以我不能覆盖它。所以我的问题也是,如何将第三方库与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()
我在这里问了一个类似的问题: 问题是您的函数可能受到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将在它当前运行的内容和您的进程之间进行纯线程切换时做一些其他事情。这对我来说似乎很好
换句话说,您可以在executor中包装子流程,并且它将被异步处理
如果您不想使用执行器,那么您的函数似乎需要以状态机的方式实现
另一篇文章:
请注意,Momoko(Postgres)和Motor(MongoDB)都是I/O绑定的
编辑:
我不知道你对龙卷风有什么用。我在做大量I/O时使用Tornado,因为我受I/O限制。然而,我想如果您的使用更受CPU的限制,您可能会想看看Flask。您可以轻松地使用Gunicorn和Flask创建简单的内容,并利用多个核心。尝试在Tornado中使用多线程或多核会给您带来很多麻烦,因为Tornado中的很多东西都不是线程安全的
编辑2:删除了.result()调用。我在这里问了一个类似的问题: 问题是您的函数可能受到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将在它当前运行的内容和您的进程之间进行纯线程切换时做一些其他事情。这对我来说似乎很好
换句话说,您可以在executor中包装子流程,并且它将被异步处理
如果您不想使用执行器,那么您的函数似乎需要以状态机的方式实现
另一篇文章:
请注意,Momoko(Postgres)和Motor(MongoDB)都是I/O绑定的
编辑:
我不知道你对龙卷风有什么用。我在做大量I/O时使用Tornado,因为我受I/O限制。然而,我想如果您的使用更受CPU的限制,您可能会想看看Flask。您可以轻松地使用Gunicorn和Flask创建简单的内容,并利用多个核心。尝试在Tornado中使用多线程或多核会给您带来很多麻烦,因为Tornado中的很多东西都不是线程安全的
编辑2:删除了.result()调用。您将在运行的some\u long\u函数中添加什么内容?我已经按照你的建议更改了测试…仍然不走运(检查更新)。你能给我看看你的代码吗?长时间运行的函数基本上是没有括号的函数名。任何变量都用逗号传递。就是这样!我正在更新我的问题,使其具有解决方案。没问题。抱歉.result()调用。您会在运行的some\u long\u函数中添加什么?我已经按照你的建议更改了测试…仍然不走运(检查更新)。你能给我看看你的代码吗?长时间运行的函数基本上是没有括号的函数名。任何变量都用逗号传递。就是这样!我正在更新我的问题,使其具有解决方案。没问题。很抱歉.result()调用。能否尝试删除.result()?那是我的错误。收益率应该自动得到结果。您可能正在等待result(),它会变成阻塞。您能尝试删除.result()吗?那是我的错误。收益率应该自动得到结果。您可能正在等待result(),它会变成阻塞。