我正试图让龙卷风返回一个清单。
@tornado.gen.coroutine
@tornado.web.asynchronous
def get(self, param):
...
someList = [bla,bla,bla]
self.finish(someList)
但无论什么时候我都会
HTTPRequest(protocol='http', host='tornado', method='GET', uri='/orders/submitted', version='HTTP/1.0', remote_ip='127.0.0.1', headers={'Accept-Language': 'en-US,en;q=0.8', 'Accept-Encoding': 'gzip,deflate,sdch', 'Host': 'tornado', 'Accept': 'application/json, text/plain, */*', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36', 'Connection': 'close', 'Referer': 'admin/', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Cookie': 'login="dHJ1ZQ==|1392074972|f4942e30293413717b380d1f362dd549548c404d"'})
Traceback (most recent call last):
File "/Users/ruahman/swipe-tech-apps/rpm-tornado/env/lib/python2.7/site-packages/tornado/web.py", line 1221, in _when_complete
if result.result() is not None:
File "/Users/ruahman/swipe-tech-apps/rpm-tornado/env/lib/python2.7/site-packages/tornado/concurrent.py", line 129, in result
raise_exc_info(self.__exc_info)
File "/Users/ruahman/swipe-tech-apps/rpm-tornado/env/lib/python2.7/site-packages/tornado/stack_context.py", line 302, in wrapped
ret = fn(*args, **kwargs)
File "/Users/ruahman/swipe-tech-apps/rpm-tornado/env/lib/python2.7/site-packages/tornado/gen.py", line 574, in inner
self.set_result(key, result)
File "/Users/ruahman/swipe-tech-apps/rpm-tornado/env/lib/python2.7/site-packages/tornado/gen.py", line 500, in set_result
self.run()
File "/Users/ruahman/swipe-tech-apps/rpm-tornado/env/lib/python2.7/site-packages/tornado/gen.py", line 531, in run
yielded = self.gen.send(next)
File "/Users/ruahman/swipe-tech-apps/rpm-tornado/fabfile/server/request_handlers/orders.py", line 26, in get
self.finish((u"hi",))
File "/Users/ruahman/swipe-tech-apps/rpm-tornado/env/lib/python2.7/site-packages/tornado/web.py", line 810, in finish
self.write(chunk)
File "/Users/ruahman/swipe-tech-apps/rpm-tornado/env/lib/python2.7/site-packages/tornado/web.py", line 610, in write
chunk = utf8(chunk)
File "/Users/ruahman/swipe-tech-apps/rpm-tornado/env/lib/python2.7/site-packages/tornado/escape.py", line 203, in utf8
"Expected bytes, unicode, or None; got %r" % type(value)
TypeError: Expected bytes, unicode, or None; got <type 'tuple'>
ERROR:tornado.access:500 GET /orders/submitted (127.0.0.1) 8424.93ms
当我返回字典时,我没有这个问题。它只发生在我返回数组时。 是的,我可以将列表嵌入到对象中,但我更喜欢将结果作为数组。
答案 0 :(得分:16)
由于复杂的原因,使用数组作为Web上JSON对象的顶级结构存在安全风险。因此,Tornado不会自动将列表转换为JSON,只会转换为dicts。我建议你把这个列表嵌入一个词典中:
self.finish({'someList': someList})
如果你坚持直接返回列表,你可以自己进行JSON编码:
self.finish(json.dumps(someList))
以下是与在Web API中使用顶级JSON数组相关的安全漏洞的说明: