标签:
Tornado的搭建很简单,使用pip,或者下载源码均可。
我们先看一个最简单的程序:
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("<h1>Hello World<h1>") application = tornado.web.Application([(r"/", MainHandler),]) if __name__ == ‘__main__‘: application.listen(8888) tornado.ioloop.IOLoop.instance().start()
我们运行这个程序,打开浏览器输入:
http://localhost:8888/
就可以看到加粗的helloworld。
那么这段代码到底什么意思:
我们先看
class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world")
这里定义了一个处理器,里面定义个一个get方法,对应Http协议中的GET请求。
然后是:
application = tornado.web.Application([ (r"/", MainHandler), ])
这里的含义是:如果用户输入的路径是“/”,也就是根路径,那么将使用我们刚才编写的MainHandler,如果该请求使用的GET,那么调用MainHandler的get方法,如果是POST请求,则去调用MainHandler中的post方法。
所以我们输入上面的网址,tornado调用了MainHandler中的get方法,返回"<h1>Hello World<h1>"
Python Tornado框架的初步使用-hello,world
标签:
原文地址:http://www.cnblogs.com/inevermore/p/4190289.html