为什么 bottle return 不列出?
Why doesn't bottle return lists?
(注意:这是一个 duplicate,我投票决定关闭它,但它可能永远不会发生所以我把信息放在显着位置,因为我不知道黄色信息横幅是否每个人或只有我看到了一个可能的重复)
我想 return 使用 bottle
:
的列表的 JSON 表示
import bottle
def ret_dict():
return {
"who": {"name": "John"}
}
def ret_list():
return [
{"name": "John"}
]
app = bottle.Bottle()
app.route('/dict', 'GET', ret_dict)
app.route('/list', 'GET', ret_list)
app.run()
调用 http://127.0.0.1:8080/dict
returns {"who": {"name": "John"}}
并且 Content-Type
设置为 application/json
。这个可以。
正在调用 http://127.0.0.1:8080/list
return500
:
Error: 500 Internal Server Error Sorry, the requested URL
'http://127.0.0.1:8080/list' caused an error:
Unsupported response type: < class 'dict' >
Python 控制台上没有错误也没有回溯。
同时一个列表可以序列化为JSON:
>>> import json
>>> json.dumps([{"name": "John"}])
'[{"name": "John"}]'
为什么 bottle
在尝试 return a list
时会引发错误?(很高兴 returning a dict
)
Bottle 的 JSON 插件只能 return dict
类型的对象 - 不能 list
。存在与 returning JSON 数组相关的漏洞 - 请参阅 this post about JSON hijacking.
作为一种解决方法,您可以将 list
对象包装在 dict
下,并用一些键表示,data 为:
def ret_list():
my_data = [
{"name": "John"}
]
return {'data': my_data}
另请阅读Vinay's answer to "How do I return a JSON array with Bottle?"。
(注意:这是一个 duplicate,我投票决定关闭它,但它可能永远不会发生所以我把信息放在显着位置,因为我不知道黄色信息横幅是否每个人或只有我看到了一个可能的重复)
我想 return 使用 bottle
:
import bottle
def ret_dict():
return {
"who": {"name": "John"}
}
def ret_list():
return [
{"name": "John"}
]
app = bottle.Bottle()
app.route('/dict', 'GET', ret_dict)
app.route('/list', 'GET', ret_list)
app.run()
调用 http://127.0.0.1:8080/dict
returns {"who": {"name": "John"}}
并且 Content-Type
设置为 application/json
。这个可以。
正在调用 http://127.0.0.1:8080/list
return500
:
Error: 500 Internal Server Error Sorry, the requested URL
'http://127.0.0.1:8080/list' caused an error:
Unsupported response type: < class 'dict' >
Python 控制台上没有错误也没有回溯。
同时一个列表可以序列化为JSON:
>>> import json
>>> json.dumps([{"name": "John"}])
'[{"name": "John"}]'
为什么 bottle
在尝试 return a list
时会引发错误?(很高兴 returning a dict
)
Bottle 的 JSON 插件只能 return dict
类型的对象 - 不能 list
。存在与 returning JSON 数组相关的漏洞 - 请参阅 this post about JSON hijacking.
作为一种解决方法,您可以将 list
对象包装在 dict
下,并用一些键表示,data 为:
def ret_list():
my_data = [
{"name": "John"}
]
return {'data': my_data}
另请阅读Vinay's answer to "How do I return a JSON array with Bottle?"。