高性能restful服务器,高性能web服务器框架Tornado简单实现restful接口及开发实例

有个朋友让我搞搞tornado框架,说实话,这个框架我用的不多。。。

我就把自己的一些个运维研发相关的例子,分享给大家。

b07169249cf722b81eb642e89fc87522.png

怎么安装tornado,我想大家都懂。

pip install tornado

再来说说他的一些个模块,官网有介绍的。我这里再啰嗦的复读机一下,里面掺夹我的理解。

主要模块

web - friendfeed 使用的基础 web 框架,包含了 tornado 的大多数重要的功能,反正你进入就对了。

escape - xhtml, json, url 的编码/解码方法

database - 对 mysqldb 的简单封装,使其更容易使用,是个orm的东西。

template - 基于 python 的 web 模板系统,类似jinja2

httpclient - 非阻塞式 http 客户端,它被设计用来和 web 及 httpserver 协同工作,这个类似加个urllib2

auth - 第三方认证的实现(包括 google openid/oauth、facebook platform、yahoo bbauth、friendfeed openid/oauth、twitter oauth)

locale - 针对本地化和翻译的支持

options - 命令行和配置文件解析工具,针对服务器环境做了优化,接受参数的

底层模块

httpserver - 服务于 web 模块的一个非常简单的 http 服务器的实现

iostream - 对非阻塞式的 socket 的简单封装,以方便常用读写操作

ioloop - 核心的 i/o 循环

再来说说tornado接受请求的方式:

关于get的方式

class mainhandler(tornado.web.requesthandler):

def get(self):

self.write("you requested the main page")

class niubi(tornado.web.requesthandler):

def get(self, story_id):

self.write("xiaorui.cc niubi'id is " + story_id)

application = tornado.web.application([

(r"/", mainhandler),

(r"/niubi/([0-9]+)", niubi),

])

这样我们访问 /niubi/123123123 就会走niubi这个类,里面的get参数。

关于post的方式

class mainhandler(tornado.web.requesthandler):

def get(self):

self.write('

'

''

''

'

')

def post(self):

self.set_header("content-type", "text/plain")

self.write("xiaorui.cc and " + self.get_argument("message"))

在tornado里面,一般get和post都在一个访问路由里面的,只是按照不同method来区分相应的。

扯淡的完了,大家测试下get和post。

import tornado.ioloop

import tornado.web

import json

class hello(tornado.web.requesthandler):

def get(self):

self.write('hello,xiaorui.cc')

class add(tornado.web.requesthandler):

def post(self):

res = add(json.loads(self.request.body))

self.write(json.dumps(res))

def add(input):

sum = input['num1'] + input['num2']

result = {}

result['sum'] = sum

return result

application = tornado.web.application([

(r"/", hello),

(r"/add", add),

])

if __name__ == "__main__":

application.listen(8888)

tornado.ioloop.ioloop.instance().start()

#大家可以写个form测试,也可以用curl -d测试

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值