如何使用Bottle返回JSON数组? [英] How do I return a JSON array with Bottle?

查看:328
本文介绍了如何使用Bottle返回JSON数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Bottle 编写API,到目前为止,这太棒了.但是,在尝试返回JSON数组时遇到了一个小障碍.这是我的测试应用代码:

I'm writing an API using Bottle, which so far has been fantastic. However, I've run up against a small hurdle when trying to return a JSON array. Here's my test app code:

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)

运行此命令并请求每条路线时,我会从前两条路线获得所需的JSON响应:

When I run this and request each route, I get the JSON responses I'd expect from the first two routes:

/单

{ id: 1, name: "Test Item 1" }

/containsarray

{ "items": [ { "id": 1, "name": "Test Item 1" }, { "id": 2, "name": "Test Item 2" } ] }

因此,我曾期望返回一个字典列表来创建以下JSON响应:

So, I had expected returning a list of dictionaries to create the following JSON response:

[ { "id": 1, "name": "Test Object 1" }, { "id": 2, "name": "Test Object 2" } ]

但是请求/array路由只会导致错误.我在做什么错,如何以这种方式返回JSON数组?

But requesting the /array route just results in an error. What am I doing wrong, and how can I return a JSON array in this manner?

推荐答案

Bottle的JSON插件期望仅返回字典,而不返回数组.与返回的JSON数组相关联的漏洞-例如,参见有关JSON劫持的帖子

Bottle's JSON plugin expects only dicts to be returned - not arrays. There are vulnerabilities associated with returning JSON arrays - see for example this post about JSON hijacking.

如果您确实需要执行此操作,则可以完成此操作,例如

If you really need to do this, it can be done, e.g.

@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)

这篇关于如何使用Bottle返回JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆