Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why tornado asynchronous doesn't work

Today, when I want to make some Synchronous Python Library to functioning asynchronously, but it doesn't work. After a series of testing, I found that even the yield tornado.gen.sleep(N) functioning synchronously.

Here's my code:

import time
import tornado.web
import tornado.gen
import tornado.ioloop
import os


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("test.htm")


class SleepHandler(tornado.web.RequestHandler):
    def get(self):
        time.sleep(2)
        self.write("Good morning!")


class YSleepHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        yield tornado.gen.sleep(2)
        self.write("Good morning!")


def main():
    app = tornado.web.Application([
        (r"/sleep", SleepHandler),
        (r"/ysleep", YSleepHandler),
        (r"/", MainHandler),
        ], debug=True, template_path=os.path.split(
            os.path.realpath(__file__))[0])
    app.listen(8888)
    try:
        tornado.ioloop.IOLoop.current().start()
    except:
        tornado.ioloop.IOLoop.current().stop()


if __name__ == "__main__":
    main()

I use the code below to test out the asynchronous function works or not(in test.htm -- template file for MainHandler):

for(var i = 0; i < 10; i++){
                $.get("/sleep");
            }
for(var i = 0; i < 10; i++){
                $.get("/ysleep");
            }

But finally, I got an unexpected result.

What's the matter? I tried under both Python2.7 and Python3.4 environment.

like image 973
Kaede Hoshikawa Avatar asked Aug 04 '26 04:08

Kaede Hoshikawa


1 Answers

Finally, this problem has been resloved by adding some unique useless arguments to the end of the URL.

for(var i = 0; i < 10; i++){
                $.get("/sleep");
            }
for(var i = 0; i < 10; i++){
                $.get("/ysleep");
            }

If you use the code above to test out the result, you will receive the same result like you're using synchronous code(Because tornado will return 304 not modified, it's a synchronous function.). but if use the use the code below, the differences between synchronous and asynchronous will be illustrated totally.

for(var i = 0; i < 10; i++){
                $.get("/sleep", {"random": Math.random()});
            }
for(var i = 0; i < 10; i++){
                $.get("/ysleep", {"random": Math.random()});
            }
like image 97
Kaede Hoshikawa Avatar answered Aug 06 '26 20:08

Kaede Hoshikawa