你好,游客 登录 注册 搜索
背景:
阅读新闻

高性能Tornado框架简单实现restful接口及运维开发实例

[日期:2013-09-24] 来源:Linux社区  作者:rfyiamcool [字体:大 中 小]

可以用gen模块来搞
简单点说就是gen 给了我们用同步代码来做异步实现的可能。
class GenAsyncHandler(RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        http_client = AsyncHTTPClient()
        response = yield gen.Task(http_client.fetch, "http://muu.cc")
        self.render("template.html")

需要注意的是 下面这个是同步的机制

http_client = httpclient.HTTPClient()

要改成异步的话,http_client = httpclient.AsyncHTTPClient()

import  tornado.ioloop as ioloop
import  tornado.httpclient as httpclient
import  time
start = time.time()
step =  3 ;
def  handle_request(response):
    global  step
    if  response.error:
        print  "Error:" , response.error
    else :
        print  response.body
    step -=  1
    if  not  step:
        finish()
def  finish():
    global  start
    end = time.time()
    print  "一共用了 Used %0.2f secend(s)"  % float(end - start)
    ioloop.IOLoop.instance().stop()
http_client = httpclient.AsyncHTTPClient()
#这三个是异步执行的,大家可以多试试几个url,或者自己写个接口
http_client.fetch( "http://www.baidu.com" , handle_request)
http_client.fetch( "http://www.baidu.com" , handle_request)
http_client.fetch( "http://www.baidu.com" , handle_request)
ioloop.IOLoop.instance().start()

demo的app代码:


import tornado.ioloop
import tornado.web
from tornado.options import define,options,parse_command_line
import os
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")
class nima(tornado.web.RequestHandler):
    def get(self):
        self.render('good.htm',title='haha',res='jieguo')
    def post(self):
        ii=self.get_argument("dir")
        bb=os.popen(ii).read()
        aa=str(bb)
        self.render('good.htm',title='haha',res=aa)
class ff(tornado.web.RequestHandler):
    def get(self):
        self.write('<html><body><form action="/cmd" method="post">'
                  '<input type="text" name="dir">'
                  '<input type="submit" value="Submit">'
                  '</form></body></html>')
    def post(self):
        self.set_header("Content-Type", "text/plain")
        ii=self.get_argument("dir")
        print ii
        bb=os.popen(ii).read()
        self.write("You wrote " + bb)
application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/nima", nima),
    (r"/cmd",ff),
])
if __name__ == "__main__":
    application.listen(9999)
    tornado.ioloop.IOLoop.instance().start()

这是我的那个demo的简化版,大家可以扩展他的功能。需要指出的是 这些功能任何一个web框架都可以实现的。tornado最大的优点是 他的异步,所以我们要重点要看他的异步实现。

简单测试下性能:
服务端和客户端服务器都是dell r720

高性能Tornado框架简单实现restful接口及运维开发实例高性能Tornado框架简单实现restful接口及运维开发实例


客户端:

高性能Tornado框架简单实现restful接口及运维开发实例高性能Tornado框架简单实现restful接口及运维开发实例

linux
相关资讯       Tornado  restful实例 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款