set_header 设置响应头
clear_header 清除响应头
add_header 增加响应头
self.flush self.finish 中断
set_status 设置状态码
工作流程
lesso3.py
1 # -*- coding:utf-8 -*- 2 3 import tornado.web 4 import tornado.httpserver 5 import tornado.options 6 import tornado.ioloop 7 from tornado.options import define,options 8 9 define(‘port‘, default=8080, help=‘run port‘, type=int) 10 define(‘version‘, default=‘0.0.1‘, help=‘version 0.0.1‘, type=str) 11 12 13 class SetHandler(tornado.web.RequestHandler): 14 15 def get(self): 16 self.write(‘set_header‘) 17 self.set_header(‘aaa‘,111) # 设置响应头 18 self.set_header(‘ccc‘,222) 19 self.set_header(‘ccc‘,333) # 重复这是会覆盖前面的 20 self.clear_header(‘ccc‘) # 清除响应头 21 self.add_header(‘ccc‘,333) # 增加响应头 22 23 24 class AddHandler(tornado.web.RequestHandler): 25 26 def get(self): 27 self.write(‘add_header‘) 28 self.add_header(‘abc‘,444) # 增加响应头 29 30 31 class SendHandler(tornado.web.RequestHandler): 32 33 def get(self): 34 self.write(‘send_error <br>‘) 35 # self.flush() # 如果加上这个flush会小小的中断一下 后面的send_error 不会执行 write 会执行 36 # self.finish() # 如果加上这个finish会彻底中断,后面的任何指令都不会执行 37 self.write(‘我被执行了‘) 38 self.send_error(404) 39 40 41 class NotFoundHandler(tornado.web.RequestHandler): 42 43 def get(self, *args, **kwargs): 44 self.send_error(404) 45 46 def write_error(self, status_code, **kwargs): 47 self.render(‘error.html‘) 48 49 50 51 class StatusHandler(tornado.web.RequestHandler): 52 53 def get(self, *args, **kwargs): # 重写状态码 54 self.write(‘set_status‘) 55 self.set_status(200,‘every good !‘) 56 57 58 ‘‘‘工作流程‘‘‘ 59 class IndexHandler(tornado.web.RequestHandler): 60 61 def set_default_headers(self): 62 print(‘-----set_default_headers:设置headers----‘) 63 64 def initialize(self): 65 print(‘----initialize: 初始化----‘) 66 67 def prepare(self): 68 print(‘----prepare:准备工作----‘) 69 70 def get(self, *args, **kwargs): 71 self.write(‘----get 处理请求----‘) 72 73 def post(self, *args, **kwargs): 74 self.write(‘----post 处理请求----‘) 75 76 def write_error(self, status_code, **kwargs): 77 self.render(‘error.html‘) 78 79 def on_finish(self): 80 print(‘----on_finish: 处理结束 释放资源----‘) 81 82 83 84 85 application = tornado.web.Application( 86 handlers = [ 87 (r"/",SetHandler), 88 (r"/add",AddHandler), 89 (r"/send",SendHandler), 90 (r"/status",StatusHandler), 91 (r"/index",IndexHandler), 92 (r"/(.*)",NotFoundHandler), 93 ], 94 template_path = ‘./error‘, 95 debug = True, 96 ) 97 98 if __name__ == ‘__main__‘: 99 print(options.port) 100 print(options.version) 101 tornado.options.parse_command_line() 102 http_server = tornado.httpserver.HTTPServer(application) 103 http_server.listen(options.port) 104 tornado.ioloop.IOLoop.instance().start()
原文地址:https://www.cnblogs.com/zlsgh/p/8478463.html
时间: 2024-10-01 02:42:11