class MainHandler(tornado.web.RequestHandler):
def get(self):
'''
The below is only a testing which will be exected to kill time,
and then we can find the asynchronous effect from the front page.
'''
for i in range(1, 100000):
print "kill time"
self.write("hello")
import logging
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.httpclient import AsyncHTTPClient
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
http = tornado.httpclient.AsyncHTTPClient()
http.fetch("http://localhost:8084/async-sync-test/", callback=self._test_callback)
self.write("Hello to the Tornado world! ")
'''
Flushes the current output buffer to the network.
'''
self.flush()
'''
_test_callback is a callback function used for the processing of the response from the async request
'''
def _test_callback(self, response):
self.write(response.body)
'''
refer the offical document, we are responsible for the invocation of the finish function in the async case.
'''
self.finish()
settings = {
#"debug": True,
}
application = tornado.web.Application([
(r"/", MainHandler),
], **settings)
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8083)
tornado.ioloop.IOLoop.instance().start()
分别启动async_sync_test_invoke3.py , async_test3.py
我们访问http://localhost:8083/的时候,可以在页面上看到较为明显的异步效果,“hello”的内容是在稍后的response中获得的。
小结:
如果是sync I/O,我们只启动一个类似sync_test代码(此处并没有提供),同样访问http://localhost:8083/程序将会整个被http error提醒,因为这里无法成功连接预期http resource,程序的线性表现在此看见。
如果是async I/O,我们只启动async_test3.py,从页面角度的看至少能获得“Hello to the Tornado world!”内容,丢失的是异步部分的内容,当然后台会有错误输出。
通过合理使用sync/async I/O,可以给web应用不错的性能,以及带来不错的用户体验
请大家帮忙指正及建议,如果有理解错误的地方!