tornado简单实现restful接口1

tornado简单实现restful接口

tornado - 异步web框架,性能很好,生产环境下用Nginx代理

主要功能看web.py
核心io循环,高级功能看ioloop.py
模板看template.py
db看torndb.py(3.1已经挑出来做成单独库了)

get/post及json使用:

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
import tornado.ioloop
import tornado.web
import json
 
class MainHandler(tornado.web.RequestHandler):
     def get( self ):
         self .write( "Hello, World" )
 
 
# 访问: http://localhost:8888/story/sishen232
# 显示:U get story id is sishen232
class StoryHandler(tornado.web.RequestHandler):
     def get( self , story_id):
         self .write( "U get story id is " + story_id)
 
 
class AddHandler(tornado.web.RequestHandler):
     # 这里可以用get的form信息,也可以直接用curl来post json数据
 
     def post( self ):
         raw_data = self .request.body
         print "raw:" , raw_data
         res = json.loads(raw_data)
         s = res[ "num1" ] + res[ "num2" ]
         self .write(json.dumps({ "sum" :s}))
 
 
application = tornado.web.Application([
     (r "/" , MainHandler),
     (r "/story/(sishen[0-9]+)" , StoryHandler), # 正则url映射,方便get
     (r "/add" , AddHandler),
])
 
if __name__ = = "__main__" :
     application.listen( 8888 )
     tornado.ioloop.IOLoop.instance().start()

测试:

?

1
flyking@wf - vm - slave1:~$ curl - d '{"num1": 3, "num2": 5}' "http://localhost:8888/add"

结果:

?

1
{ "sum" : 8 }


你可能感兴趣的:(tornado简单实现restful接口1)