tornado异步请求的理解(转)
2014-10-29 11:00
169 查看
tornado异步请求的理解
http://www.kankanews.com/ICkengine/archives/88953.shtml
官网第一段话:
Tornado is a Python web framework and
asynchronousnetworking library, originally developed at FriendFeed. By using non-blocking network I/O, Tornado can scale to tens of thousands of open connections, making it ideal for long polling, WebSockets, and other applications that require a long-lived connection to each user.
翻译理解一下:Tornado是一个python实现的web框架,是
异步网络请求包,起源于friendFeed; 是
无阻塞网络I/O, Tornado可以很好处理成千上万的连接(C10K);处理轮询,webSockets和其他应用长连接等请求
个人理解异步网络等同于无阻塞网络
在官网中提供的一个Hello world的这个Demo中,是
不支持异步的,只有在使用
@tornado.web.asynchronous这个装饰器的时候才能算的上真正异步;参考博客
在blog中还有一个装饰
@tornado.gen.coroutine这个装饰器是干什么的呢?? 查看tornado源码在gen.py中
For example, the following asynchronous handler::
class AsyncHandler(RequestHandler): @asynchronous def get(self): http_client = AsyncHTTPClient() http_client.fetch("http://example.com", callback=self.on_fetch) def on_fetch(self, response): do_something_with_response(response) self.render("template.html") self.finish()
从上面的代码可以看出在使用
@asynchronous的时候,而且需要注意的是 Tornado默认在函数处理返回时关闭客户端的连接,但是当你使用@tornado.web.asynchonous装饰器时,Tornado永远不会自己关闭连接,需要显式的
self.finish()关闭;每次需要一个显示命名一个callBack方法,为了
省略写这个方法和
self.finish(),
就有如下的代码:
Future方式:
class GenAsyncHandler(RequestHandler): @asynchronous @gen.coroutine def get(self): http_client = AsyncHTTPClient() response = yield http_client.fetch("http://example.com") do_something_with_response(response) self.render("template.html")
Task方式:
class GenAsyncHandler2(RequestHandler): @asynchronous @gen.coroutine def get(self): http_client = AsyncHTTPClient() http_client.fetch("http://example.com", callback=(yield gen.Callback("key")) # 1 response = yield gen.Wait("key") # 2 do_something_with_response(response) self.render("template.html")
并且
@gen.coroutine和
yield都是配对使用的
Task方式改良版:
细看gen.py注释文档我们会发现还有一种方式可以省略装饰器@asynchronous和简化#1和#2代码, 使用gen.Task
@gen.coroutine def get(self): yield gen.Task(AsyncHTTPClient().fetch, "http://example.com")#替换上面的#1和#2
一次异步多个请求,适用于Future和Task版, 以下是Future版本
@gen.coroutine def get(self): http_client = AsyncHTTPClient() response1, response2 = yield [http_client.fetch(url1), http_client.fetch(url2)]
自己理解,仅供参考;
声明:OSCHINA 博客文章版权属于作者,受法律保护。未经作者同意不得转载。
No tags for this post.
除非注明,本站文章均为原创或编译,转载请注明: 文章来自KENGINE | Kankanews.com
相关文章推荐
- 使用tornado让你的请求异步非阻塞
- 使用tornado让你的请求异步非阻塞
- tornado使用celery的请求异步非阻塞
- [翻译]深入理解Tornado——一个异步web服务器
- tornado异步请求非阻塞
- 【C#】对异步请求处理程序IHttpAsyncHandler的理解和分享一个易用性封装 【手记】走近科学之为什么明明实现了IEnumerable<T>的类型却不能调用LINQ扩展方法 【手记】手机网页弹出层后屏蔽底层的滑动响应 【手记】ASP.NET提示“未能创建类型”处理 【Web】一个非常简单的移动web消息框 【手记】解决EXCEL跑SQL遇“查询无法运行或数据库表无法打开...”
- 关于自己对okhttp的理解-----get请求异步用法
- 理解同步请求和异步请求
- 深入理解Tornado——一个异步web服务器
- tornado异步web请求
- 使用tornado如何实现请求异步非阻塞?
- 一段简单代码理解异步请求消息队列在高并发环境中的作用
- 使用tornado让你的请求异步非阻塞
- tornado异步请求非阻塞
- tornado中epoll的异步请求的实现过程
- 深入理解Tornado——一个异步web服务器
- 使用tornado让你的请求异步非阻塞
- 关于自己对okhttp的理解-----get请求异步用法
- 使用tornado让你的请求异步非阻塞
- 利用tornado使请求实现异步非阻塞