def write(self, chunk, status=None): """Writes the given chunk to the output buffer. To write the output to the network, use the flush() method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call set_header *after* calling write()). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx """ if self._finished: raise RuntimeError("Cannot write() after finish(). May be caused " "by using async operations without the " "@asynchronous decorator.") if isinstance(chunk, dict): chunk = jsonutil.json_encode(chunk) elif isinstance(chunk, list): chunk = jsonutil.json_encode({"list": chunk}) else: chunk = jsonutil.json_encode({"result": chunk}) chunk = utf8(chunk) self._write_buffer.append(chunk) self.set_header("Content-Type", "application/json; charset=UTF-8") if status is not None: self.set_status(status)
def flat_attributes(self): """ 扁平化的属性,只保留一层。 在bo转dbmodel使用 如果存在list就把list转换成字符串 如果是bo对象,就把这个对象转换成json字符串 :return: """ d = DefaultDict() for name, obj in self.class_attributes: value = getattr(self, name) if isinstance(value, BizModel): d[name] = jsonutil.json_encode(value.attributes) elif isinstance(value, (list, tuple)): if obj.generic_type and issubclass(obj.generic_type, BizModel): values = [] for v in value: values.append(v.attributes) d[name] = jsonutil.json_encode(values) else: values = [] for v in value: if isinstance(v, basestring) and obj.prefix: if v.startswith(obj.prefix): v = v.replace(obj.prefix, '', 1) values.append(v) else: values.append(v) d[name] = obj.split.join(values) else: v = getattr(self, name) if isinstance(v, basestring) and obj.prefix: if v.startswith(obj.prefix): v = v.replace(obj.prefix, '', 1) if isinstance(v, basestring) and obj.time_stamp: v = dateutil.string_to_timestamp(v) d[name] = v return d