19

我正在使用 Flask 创建一个 API,并具有以下代码:

@app.route('/<major>/')
def major_res(major):
    course_list = list(client.db.course_col.find({"major": (major.encode("utf8", "ignore").upper())}))
    return json.dumps(course_list, sort_keys=True, indent=4, default=json_util.default)

/csci/浏览器中查看时,输出如下所示:

[{ "course": "CSCI052", "description": "Fundamentals of Computer Science. A solid foundation in functional programming, procedural and data abstraction, recursion and problem-solving. Applications to key areas of computer science, including algorithms and complexity, computer architecture and organization, programming languages, finite automata and computability. This course serves the same role as HM 60 as a prerequisite for upper-division computer science courses at any of the Claremont Colleges. Prerequisite: 51.", "instructor": "Bull, Everett L.,, Jr.", "name": " Fundamentals of Computer Science", "number": 52, "school": "PO" }]

如何返回这本字典,以便每个键和值都在自己的行上?

4

2 回答 2

32

Flask 提供jsonify()了一种便利:

from flask import jsonify

@app.route("/<major>/")
def major_res(major):
    course_list = list(client.db.course_col.find({"major": major.upper()}))
    return flask.jsonify(**course_list)

这将返回 argsjsonify作为 JSON 表示,并且与您的代码不同,它将发送正确的Content-Type标头:application/json。请注意文档对格式的说明:

JSONIFY_PRETTYPRINT_REGULAR如果config 参数设置为True或 Flask 应用程序在调试模式下运行,此函数的响应将被很好地打印出来。压缩(不漂亮)格式目前意味着分隔符后没有缩进和空格。

不处于调试模式时,响应将收到非漂亮打印的 JSON。这应该不是问题,因为 JavaScript 消费的 JSON 不需要被格式化(这只是通过网络发送的额外数据),并且大多数工具格式自己接收 JSON。

如果您还想继续使用json.dumps(),可以通过返回Responsewith来发送正确的 mimetype current_app.response_class()

from flask import json, current_app

@app.route("/<major>/")
def major_res(major):
    course_list = list(client.db.course_col.find({"major": major.upper() }))
    return current_app.response_class(json.dumps(course_list), mimetype="application/json")

有关差异的更多信息:


在 Flask 1.0 之前,JSON 处理有些不同。jsonify将尝试检测请求是否为 AJAX,如果不是则返回漂亮的打印;这被删除了,因为它不可靠。出于安全原因jsonify,只允许 dicts 作为顶级对象;这不再适用于现代浏览器。

于 2013-07-18T05:18:10.393 回答
3

如果由于某种原因您需要覆盖flask.jsonify(例如,添加自定义 json 编码器),您可以使用以下实现安全修复 @phpmycoder 的方法来实现:

from json import dumps
from flask import make_response

def jsonify(status=200, indent=4, sort_keys=True, **kwargs):
    response = make_response(dumps(dict(**kwargs), indent=indent, sort_keys=sort_keys))
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    response.headers['mimetype'] = 'application/json'
    response.status_code = status
    return response

@app.route('/<major>/')
def major_res(major):
    course = client.db.course_col.find({"major": (major.encode("utf8", "ignore").upper())})
    return jsonify(**course)

@app.route('/test/')
def test():
    return jsonify(indent=2, sort_keys=False, result="This is just a test")

回复:

{
    "course": "CSCI052", 
    "description": "Fundamentals of Computer Science. A solid foundation in functional programming, procedural and data abstraction, recursion and problem-solving. Applications to key areas of computer science, including algorithms and complexity, computer architecture and organization, programming languages, finite automata and computability. This course serves the same role as HM 60 as a prerequisite for upper-division computer science courses at any of the Claremont Colleges. Prerequisite: 51.", 
    "instructor": "Bull, Everett L.,, Jr.", 
    "name": " Fundamentals of Computer Science", 
    "number": 52, 
    "school": "PO"
}
于 2014-04-27T07:32:37.757 回答