Home  >  Article  >  Backend Development  >  高性能web服务器框架Tornado简单实现restful接口及开发实例

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

WBOY
WBOYOriginal
2016-06-16 08:43:122936browse

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

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

怎么安装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测试

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn