tornado简单实现restful接口2

http头部和http_code状态码处理

@tornado.web.asynchronous
     def post(self):
         """Handle POST requests."""
         # Disable caching
         self.set_header("Cache-Control","no-cache, must-revalidate")
         self.set_header("Expires","Mon, 26 Jul 2013 05:00:00 GMT")
         self.poll_start = time.time()
         action = self.get_argument("action")
         if action=="poll":
             self.poll()
         elif action=="message":
             self.process_incoming(self.get_argument("message"))
         else:
             self.set_status(400)
             self.finish()

获取所有输入数据,存储起来方便处理:

class BaseHandler(tornado.web.RequestHandler):
    def recvData(self):
        data = defaultdict(lambda : None)
        # 获得所以输入参数,并存在data中
        args = self.request.arguments
        for a in args:
            data[a] = self.get_argument(a)
        # 获取file类型参数
        data["files"] = self.request.files
        # 获取headers
        data["headers"] = self.request.headers

        return data

通过正则匹配url返回json

from datetime import date

import tornado.escape
import tornado.ioloop
import tornado.web
                                                                    
class VersionHandler(tornado.web.RequestHandler):
    def get(self):
        response = { 'version': '3.5.1',
                     'last_build':  date.today().isoformat() }
        self.write(response)
                                                                                                     
class GetGameByIdHandler(tornado.web.RequestHandler):
    def get(self, _id):
        response = { 'id': int(_id),
                     'name': 'Crazy Game',
                     'release_date': date.today().isoformat() }
        self.write(response)
                                                                                                
application = tornado.web.Application([
    (r"/getgamebyid/([0-9]+)", GetGameByIdHandler),
    (r"/version", VersionHandler)
])
                                                                                                                                                                                                
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

输入:  http://localhost:8888/version 
结果: {"last_build": "2013-10-22", "version": "3.5.1"}

转载于:https://my.oschina.net/1123581321/blog/170545

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值