1.构建具体执行handler
#定义类继承 tornado.web.RequstHandler
class IndexHandler(tornado.web.RequestHandler):
#如果是get方法,定义get函数
def get(self):
greeting = self.get_argument('greeting', 'Hello')#get_argument函数获取上传的参数,第一个是key,第二个是为获取到值时的默认值
self.write(greeting + ', friendly user!')#返回请求给浏览器
#如果是post方法,定义post函数
2.构建Server listen
app = tornado.web.Application(handlers=[(r"/", IndexHandler)])#定义一个web application,handlers数列里放url与handler对应关系,以元组形式
http_server = tornado.httpserver.HTTPServer(app)#定义server
http_server.listen(8080,"127.0.0.1")#监听的端口,以及Ip地址
tornado.ioloop.IOLoop.instance().start()#启动server
3.完整代码
# coding:utf-8
# python3.6
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 the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
greeting = self.get_argument('greeting', 'Hello')
self.write(greeting + ', friendly user!')
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
4.结果
python3 hello.py
请求 127.0.0.1:8000/
得到Hello, friendly user!
或者
请求 127.0.0.1:8000?greeting=max
得到max,friendly user!