简体   繁体   English

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

[英]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.

相关问题 Flask返回TypeError:视图函数未返回有效响应 - Flask is returning TypeError: The view function did not return a valid response 如何解决TypeError: The view function did not return a valid response in python flask api - How to solve the TypeError: The view function did not return a valid response in python flask api Flask应用程序中的“视图功能未返回有效响应。”错误在哪里? - Where is the “The view function did not return a valid response.” error in my Flask app? 错误在哪里?“视图函数未返回有效响应。 ”在我的烧瓶应用程序中? - Where is the error “The view function did not return a valid response. ” in my flask app? Flask 视图返回错误“视图函数未返回响应” - Flask view return error "View function did not return a response" 查看功能未在烧瓶中返回响应 - View function did not return a response in flask Flask TypeError:“**”的视图 function 未返回有效响应。 function 要么返回 None 要么在没有返回语句的情况下结束 - Flask TypeError: The view function for '**' did not return a valid response. The function either returned None or ended without a return statement FLASK-python ValueError:视图函数未返回响应 - FLASK-python ValueError: View function did not return a response 查看功能未返回响应 - View function did not return a response “运行”的视图 function 未返回有效响应。 function 返回 None 或结束时没有返回语句 - The view function for 'run' did not return a valid response. The function either returned None or ended without a return statement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM