tornado write render redirect IP
write 用法( self.flush() )
render (跳转指定网页)用法
redirect(跳转指定路由)用法
self.request.remote_ip 显示用户 IP 地址
lesson2.py
1 # -*- coding:utf-8 -*- 2 3 import tornado.web 4 import tornado.httpserver 5 import tornado.options 6 import tornado.ioloop 7 import time 8 import json 9 from tornado.options import define,options 10 11 define('port', default = 8080, help = 'run port', type = int) 12 define('version', default = '0.0.1', help = 'version 0.0.1', type = str) 13 14 15 class MainHandler(tornado.web.RequestHandler): 16 17 def get(self): 18 self.write('小红 <br>') # write 可传入参数类型 bytes unicode字符 字典 json 19 self.flush() # 半中断 20 time.sleep(3) 21 user={ 22 'name' : "小明", 23 'age' : 18, 24 'gender' : 'male' 25 } 26 self.write(user) 27 self.flush() 28 self.write('<br>') 29 li = [1,2,3,4,5] 30 li = json.dumps(li) # write 传入json 时,html语法不会解析,原样输出,直到有 self.flush() 31 self.write(li) 32 self.flush() 33 34 '''打开指定网页''' 35 class TemHandler(tornado.web.RequestHandler): 36 37 def get(self): 38 self.render('01in-out.html') 39 40 41 '''跳转指定路由''' 42 class RecHandler(tornado.web.RequestHandler): 43 44 def get(self): 45 self.redirect("/tem") 46 47 48 '''查看访问服务器的IP地址''' 49 class ReqHandler(tornado.web.RequestHandler): 50 51 def get(self): 52 self.write(self.request.remote_ip) # 浏览器显示IP地址 53 print(type(self.request.remote_ip),repr(self.request.remote_ip)) # 显示在后台服务器上 54 print(self.request.full_url) 55 56 57 application = tornado.web.Application( 58 handlers = [ 59 (r"/",MainHandler), 60 (r"/tem",TemHandler), 61 (r"/rec",RecHandler), 62 (r"/req",ReqHandler), 63 ], 64 template_path = 'esle', 65 debug = True 66 ) 67 68 69 if __name__ == '__main__': 70 print(options.port) 71 print(options.version) 72 tornado.options.parse_command_line() 73 http_server = tornado.httpserver.HTTPServer(application) 74 http_server.listen(options.port) 75 tornado.ioloop.IOLoop.instance().start()
2018-02-27 13:40:59