tornado - 异步web框架,性能很好,生产环境下用Nginx代理
主要功能看web.py
核心io循环,高级功能看ioloop.py 模板看template.py db看torndb.py(3.1已经挑出来做成单独库了)get/post及json使用:
#!/usr/bin/env python# -*- coding:utf-8 -*-import tornado.ioloopimport tornado.webimport jsonclass MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, World")# 访问: http://localhost:8888/story/sishen232# 显示:U get story id is sishen232class 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()测试:
flyking@wf-vm-slave1:~$ curl -d '{"num1": 3, "num2": 5}' "http://localhost:8888/add"结果:
{"sum": 8}