Flask REST API错误:视图函数未返回有效响应

时间:2019-07-28 12:22:47

标签: python python-3.x rest flask

在Python中的Flask REST API路由中,返回类型为list

@app.route('/ent', methods=['POST'])
def ent():
    """Get entities for displaCy ENT visualizer."""
    json = request.get_json()
    nlp = MODELS[json['model']]
    doc = nlp(json['text'])
    return [
        {"start": ent.start_char, "end": ent.end_char, "label": ent.label_}
        for ent in doc.ents
    ]

此错误:

TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.

如何获取/ent上的API路由以正确返回JSON数组?

2 个答案:

答案 0 :(得分:2)

您可以随时根据Flask的需要将列表转换为字典,如下所示

return { "data": [
        {"start": ent.start_char, "end": ent.end_char, "label": ent.label_}
        for ent in doc.ents
    ]}

您还看过Flask REST API responding with a JSONArray吗?

答案 1 :(得分:1)

失败的原因是因为Flask中的视图需要可哈希的返回类型。您始终可以将返回值转换为可哈希类型,即字符串,字典,元组等,然后从结果进行转换。

return tuple([
        {"start": ent.start_char, "end": ent.end_char, "label": ent.label_}
        for ent in doc.ents
    ])