Tornado之请求与响应头
import tornado.ioloop
import tornado.httpserver
import tornado.web
import tornado.options
import json
import time
from tornado.options import options,define
define("port",default=8080,help="run port",type=int)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("我在下面!<br>")
name = self.get_argument("name","none")
self.write("这个是我:"+name)
class HeaderHandler(tornado.web.RequestHandler):
def get(self):
self.write('set_header')
self.set_header('aaa', '1111')
self.set_header('bbb', '2222')
self.set_header('bbb', '3333')
class AddHandler(tornado.web.RequestHandler):
def get(self):
self.write('add_header')
self.add_header('ccc', '3333')
self.add_header('ccc', '4444')
class CleanHandler(tornado.web.RequestHandler):
def get(self):
self.write('clear_heander')
self.add_header('abcd', '5555')
self.add_header('abcd', '6666')
self.clear_header('abcd')
class SendHandler(tornado.web.RequestHandler):
def get(self):
self.write('send_error')
'''
使用 send_error 时需要注意:如果已经执行了 flush,则不能再执行 send_error,因此该方法将简单地终止响应
如果输出已写入但尚未刷新,则将其丢弃并替换为错误页面
'''
def write_error(self, status_code, **kwargs):
self.write('status_code: %s' % status_code)
class NotFoundHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.send_error(404)
def write_error(self, status_code, **kwargs):
self.render('error_notfound.html')
class IndexHandler(tornado.web.RequestHandler):
def set_default_headers(self):
print(' ---set_default_headers---:设置header')
def initialize(self):
print(' ---initialize---:初始化')
def prepare(self):
print(' ---prepare---:准备工作')
def get(self):
self.write(' ---get---:处理get请求'+'<br>')
def post(self):
self.write(' ---post---:处理post请求'+'<br>')
def write_error(self, status_code, **kwargs):
print(' ---write_error---:处理错误')
def on_finish(self):
print(' ---on_finish---:结束,释放资源')
application = tornado.web.Application(
handlers = [
(r"/", MainHandler),
(r"/set", HeaderHandler),
(r"/add",AddHandler),
(r"/set",AddHandler),
(r"/clean",CleanHandler),
(r"/send",SendHandler),
(r"/index",IndexHandler),
(r'/(.*)', NotFoundHandler),
],
template_path = 'templates',
debug=True
)
if __name__ =="__main__":
tornado.options.parse_command_line()
http_server=tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()