tornado中self.write() 写list

tornado源码中不支持在self.write()中直接传入list对象,源代码如下

    def write(self, chunk):
if self._finished:
raise RuntimeError("Cannot write() after finish()")
if not isinstance(chunk, (bytes, unicode_type, dict)):
message = "write() only accepts bytes, unicode, and dict objects"
if isinstance(chunk, list):
message += ". Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write"
raise TypeError(message)
if isinstance(chunk, dict):
chunk = escape.json_encode(chunk)
self.set_header("Content-Type", "application/json; charset=UTF-8")
chunk = utf8(chunk)
self._write_buffer.append(chunk)

但是在某些条件下我们需要传list给前端便于前端解析,因此我们可以覆写框架中的write(不建议)或者定义我们自己的write,我自己在自己定义的基类中定义了自己的write函数,代码如下:

class BaseHandler(tornado.web.RequestHandler):
# 这是自己定义的基类,业务类继承这个基类
def __init__(self, *argc, **kwarg):
super(BaseHandler, self).__init__(*argc, **kwarg) def get_current_user(self):
return self.get_secure_cookie("user") def get(self):
self.send_error(404) def mywrite(self, chunk):
# 定义自己实现的write()方法
if self._finished:
raise RuntimeError("Cannot write() after finish()")
if not isinstance(chunk, (unicode_type, list, dict)):
message = "write() only accepts bytes, unicode, list and dict objects"
raise TypeError(message)
if isinstance(chunk, (list, dict)):
chunk = json.dumps(chunk).replace("</", "<\\/")
self.set_header("Content-Type", "application/json; charset=UTF-8")
chunk = utf8(chunk)
self._write_buffer.append(chunk) def write_error(self, status_code, **kwargs):
if status_code == 404:
self.render('public/404.html')
elif status_code == 500:
self.render('public/500.html')
else:
self.write('error' + str(status_code))

下面是业务类,继承了自己写的基类BaseHandler

class BaseHandler(BaseHandler):
# 这是这里是业务类
def get(self):
a = [1,2,3,4,5]
self.mywrite(a)
上一篇:Activiti 查看流程图


下一篇:(转)MySQL排序原理与案例分析