python - 如何使用 Bottle 返回 JSON 数组?

标签 python bottle

我正在使用 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)

当我运行它并请求每个路由时,我会从前两个路由中得到我期望的 JSON 响应:

/single

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

/containsarray

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

所以,我希望返回一个字典列表来创建以下 JSON 响应:

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

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

最佳答案

Bottle 的 JSON 插件只希望返回字典,而不是数组。存在与返回 JSON 数组相关的漏洞 - 参见示例 this post about JSON hijacking .

如果你真的需要这样做,可以这样做,例如

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

关于python - 如何使用 Bottle 返回 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12293979/

相关文章:

python - 发送不改变用户当前页面的 HTTP 响应

python - Flask 单元测试 session 装饰器

python - 将一个方法绑定(bind)到另一个类

python - BottlePy 应用程序和 CherryPy 服务器未记录访问

python - Bottle 是否处理非并发请求?

python - 如何使用 flatten_json 递归地展平嵌套的 JSON

python - 如何在Pythonista iOS中运行Flask?

python - Heroku 的 Gunicorn 和 Bottle 设置

python-2.7 - 使 Ace 编辑器在 Bottle 环境中工作所需的最少文件是多少?需要将它们放置在哪里?

python - 在 Bottle 中实现简单的验证码