龙卷风异步调用功能



我正在使用Python Tornado制作Web应用程序,该应用程序基本上将文件提供给用户。我没有数据库。

文件要么直接拾取并在可用的情况下提供服务,要么是在即时生成的。

我希望以异步方式向客户提供服务,因为某些文件可能已经可用,而其他文件需要生成(因此他们需要等待,我不希望他们阻止其他用户)。<<<<<<<<<<<<<<

我有一个管理文件或生成文件的课程,我只需要从龙卷风打电话。

实现这一目标的最佳方法(在CPU和RAM上最有效)是什么?我应该使用线程吗?一个子过程?这样的简单gen.task?

另外,我希望我的实施能够在Google App引擎上工作(我认为它们不允许产生子进程?)。

我对异步网络服务相对较新,因此欢迎任何帮助。

我找到了我问题的答案:绅士示例确实是实现异步调用的最佳方法,这是由于示例确实使用 python coroutine ,我乍一看我不了解,因为我以为 yart 仅用于返回发电机的值。

具体示例:

class MyHandler(tornado.web.RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        response = yield gen.Task(self.dosomething, 'argument')

这里重要的是两件事的组合:

  • 产量,实际上会产生一个coroutine(或伪线程,它非常有效,并且非常同意)。http://www.python.org/dev/peps/pep-0342/

  • gen.Task()是一个非阻滞(async)函数,因为如果您在阻止功能上产生coroutine,则不会是异步。gen.Task()由Tornado提供,特别是与Python的Coroutine语法合作。更多信息:http://www.tornadoweb.org/documentation/gen.html

因此,使用Coroutines在Python中进行异步调用的规范示例:

response = yield non_blocking_func(**kwargs)

现在文档已有解决方案。

简单示例:

import os.path
import tornado.web
from tornado import gen
class MyHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self, filename):
        result = yield self.some_usefull_process(filename)
        self.write(result)
    @gen.coroutine
    def some_usefull_process(self, filename):
        if not os.path.exists(filename):
            status = yield self.generate_file(filename)
            result = 'File created'
        else:
            result = 'File exists'
        raise gen.Return(result)
    @gen.coroutine
    def generate_file(self, filename):
        fd = open(filename, 'w')
        fd.write('created')
        fd.close()

最新更新