我正在使用Bottle编写一个API ,到目前为止一直很棒.但是,在尝试返回JSON数组时,我遇到了一个小障碍.这是我的测试应用代码:
from bottle import route, run
@route('/single')
def returnsingle():
return { "id": 1, "name": "Test Item 1" }
@route('/containsarray')
def returncontainsarray():
return { "items": [{ "id": 1, "name": "Test Item 1" }, { "id": 2, "name": "Test Item 2" }] }
@route('/array')
def returnarray():
return [{ "id": 1, "name": "Test Item 1" }, { "id": 2, "name": "Test Item 2" }]
run(host='localhost', port=8080, debug=True, reloader=True)
Run Code Online (Sandbox Code Playgroud)
当我运行它并请求每个路由时,我得到了前两条路线所期望的JSON响应:
/单
{ id: 1, name: "Test Item 1" }
Run Code Online (Sandbox Code Playgroud)
/ containsarray
{ "items": [ { "id": 1, "name": "Test Item 1" }, { "id": 2, "name": "Test Item 2" } ] }
Run Code Online (Sandbox Code Playgroud)
所以,我原本期望返回一个字典列表来创建以下JSON响应:
[ { "id": 1, "name": "Test Object 1" }, { "id": 2, "name": "Test Object 2" } ]
Run Code Online (Sandbox Code Playgroud)
但是请求/array路由只会导致错误.我做错了什么,如何以这种方式返回JSON数组?
Vin*_*jip 74
Bottle的JSON插件只需要返回dicts - 而不是数组.返回JSON数组存在漏洞 - 例如,有关JSON劫持的帖子.
如果你真的需要这样做,可以做到,例如
@route('/array')
def returnarray():
from bottle import response
from json import dumps
rv = [{ "id": 1, "name": "Test Item 1" }, { "id": 2, "name": "Test Item 2" }]
response.content_type = 'application/json'
return dumps(rv)
Run Code Online (Sandbox Code Playgroud)
jos*_*nez 14
根据Bottle的0.12文档:
如上所述,Python字典(或其子类)会自动转换为JSON字符串并返回到浏览器,并将Content-Type标头设置为application/json.这使得实现基于json的API变得容易.也支持json以外的数据格式.请参阅tutorial-output-filter以了解更多信息.
这意味着您不需要也不需要import json设置响应的content_type属性.
因此,代码大大减少:
@route('/array')
def returnarray():
rv = [{ "id": 1, "name": "Test Item 1" }, { "id": 2, "name": "Test Item 2" }]
return dict(data=rv)
Run Code Online (Sandbox Code Playgroud)
Web服务器返回的JSON文档如下所示:
{"data": [{"id": 1, "name": "Test Item 1"}, {"id": 2, "name": "Test Item 2"}]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29341 次 |
| 最近记录: |