Tornado Python 的异步函数调用 [英] Async function call with Tornado Python

查看:25
本文介绍了Tornado Python 的异步函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Tornado 的 gen.coroutine 函数进行简单的异步调用.这是我当前的代码:

I'm trying to make a simple async call, using gen.coroutine function of Tornado. This is my current code:

from tornado import gen
import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):

    @gen.coroutine
    def get(self):
        q = self.get_argument('query')
        print q
        response = yield self.process(q)
        self.write(response)

    @gen.coroutine
    def process(self, query):
        # just a long loop
        for i in range(int(query)*100):
            for j in range(i):
                a = 10*10*10*10*10*10
        return {'processed': True}


def make_app():
    return tornado.web.Application([
        (r"/search", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    port = 8888
    print "listening on port: ", port
    app.listen(port)
    tornado.ioloop.IOLoop.current().start()

但是,它不是以异步方式运行的.我做错了什么?

However, it is not behaving in an async manner. What am I doing wrong in this?

推荐答案

您的函数正在阻塞事件循环,并且在 process() 函数完成或放弃控制权之前无法处理其他任务回到事件循环.对于这种情况,您可以简单地使用 yield None(以前是 yield gen.moment)来休息一下,让事件循环运行其他任务,然后继续处理.示例:

Your function is blocking the event loop and no other tasks can be handled until either the process() function completes or it relinquishes control back to the event loop. For situations like this, you can use simply yield None (it used to be yield gen.moment) to take a break and let the event loop run other tasks then resume processing. Example:

@gen.coroutine
def process(self, query):
    for i in range(int(query)*100):
        for j in range(i):
            a = 10*10*10*10*10*10
            if j % 500 == 0:
                yield None    # yield the inner loop

        if i % 500 == 0:
            yield None    # yield outer loop

    return {'processed': True}

希望这有助于您实现所需的并发级别.

Hopefully this helps you achieve your desired level of concurrency.

http://www.tornadoweb.org/en/stable/gen.html#tornado.gen.moment

这篇关于Tornado Python 的异步函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆