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"}