tornado之Hello world
#!/usr/bin/env python26 #-*- coding:utf8 -*- import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define,options define("port",default=8000,help="run on this port",type=int) class TestHandler(tornado.web.RequestHandler): def get(self): self.write("Hello world!") greeting=self.get_argument('greeting','Hello') self.write(greeting+',friendly user!\n') print "*"*30 def main(): tornado.options.parse_command_line() app=tornado.web.Application(handler=[(r"/",TestHandler)]) http_server=tornado.httpserver.HTTPServer(app) try: http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt,e: print e if __name__ == "__main__": main()
上述的脚本在测试过程中,通过print发现没有输出,断定原因在于get函数没有被调用
对比之前写的代码,原来是这里写错了
app=tornado.web.Application(handlers=[(r"/",TestHandler)])
tornado.web.Application = class Application(__builtin__.object) | A collection of request handlers that make up a web application. | | Instances of this class are callable and can be passed directly to | HTTPServer to serve the application:: | | application = web.Application([ | (r"/", MainPageHandler), | ]) | http_server = httpserver.HTTPServer(application) | http_server.listen(8080) | ioloop.IOLoop.instance().start()
通过帮助文档中没有查到默认参数名是handlers,不过测试可以发现确实如此,后续可以不加上。
【参考资料】