python tornado框架使用
处理方法 t_handler.py
from tornado.web import RequestHandler class IndexHandler(RequestHandler): def get(self): name=self.get_argument('name','world') self.write('hello '+name) class AddHandler(RequestHandler): def get(self): val1=self.get_argument('val1',0) val2=self.get_argument('val2',0) val3=int(val1)+int(val2) self.write(str(val3)) class MinusHandler(RequestHandler): def get(self): val1=self.get_argument('val1',0) val2=self.get_argument('val2',0) val3=int(val1)-int(val2) self.write(str(val3))
Url路径,处理方法对应关系 t_url.py
from t_handler import * url=[ (r'/',IndexHandler), (r'/page1',AddHandler), (r'/page2',MinusHandler) ]
启动进程 t_tornado.py
tornado.options import tornado.web from tornado.options import define,options import t_url define("port",default=8000,help="run on port",type=int) if __name__=="__main__": tornado.options.parse_command_line() #初始化web框架 app=tornado.web.Application(t_url.url) #开启端口监听服务 http_server=tornado.httpserver.HTTPServer(app) http_server.listen(options.port) #启动服务进程 tornado.ioloop.IOLoop.instance().start()
运行结果:
浏览器访问结果: