[英]Flask REST API Error: The view function did not return a valid response
In a Flask REST API route in Python, the return type is a list
在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
]
This errors with: 这个错误:
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.
How can I get the API route on /ent
to return a JSON array correctly? 如何在
/ent
上获取API路由以正确返回JSON数组?
You can always convert the list into dict as needed by Flask as shown below 您可以随时根据需要将列表转换为dict,如下所示
return { "data": [
{"start": ent.start_char, "end": ent.end_char, "label": ent.label_}
for ent in doc.ents
]}
Also have you seen Flask REST API responding with a JSONArray ? 您还看到Flask REST API使用JSONArray进行响应吗?
The reason it is failing is because the views in Flask require a hashable return type. 它失败的原因是因为Flask中的视图需要一个可散列的返回类型。 You can always convert your return values to hashable types viz string, dict, tuple etc and then transform from the result.
您始终可以将返回值转换为可散列类型,即string,dict,tuple等,然后从结果转换。
return tuple([
{"start": ent.start_char, "end": ent.end_char, "label": ent.label_}
for ent in doc.ents
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.