在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数组?
答案 0 :(得分:2)
您可以随时根据Flask的需要将列表转换为字典,如下所示
return { "data": [
{"start": ent.start_char, "end": ent.end_char, "label": ent.label_}
for ent in doc.ents
]}
答案 1 :(得分:1)
失败的原因是因为Flask中的视图需要可哈希的返回类型。您始终可以将返回值转换为可哈希类型,即字符串,字典,元组等,然后从结果进行转换。
return tuple([
{"start": ent.start_char, "end": ent.end_char, "label": ent.label_}
for ent in doc.ents
])