简体   繁体   中英

In tornado ,how to make these functions async?

Here is my code:

#/test
class Test(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        res = yield self.inner()
        self.write(res)

    @tornado.gen.coroutine
    def inner(self):
        import time
        time.sleep(15)
        raise tornado.gen.Return('hello')

#/test_1
class Test1(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        res = yield self.inner()
        self.write(res)

    @tornado.gen.coroutine
    def inner(self):
        raise tornado.gen.Return('hello test1')

When I fetch /test and then fetch /test_1, but /test_1 does not response until /test responsed, how to fixed it?

Don't use time.sleep() . time.sleep() will block cpu loop. Instead, use

yield tornado.gen.Task(tornado.ioloop.IOLoop.instance().add_timeout,
                               time.time() + sleep_seconds)

You've hit both the frequently-asked questions:

http://www.tornadoweb.org/en/stable/faq.html

First, please don't use time.sleep() in a Tornado application, use gen.sleep() instead. Second, be aware that most browsers won't fetch two pages from the same domain simultaneously: use "curl" or "wget" to test your application instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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