简体   繁体   English

如何解决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

I am trying to retrieve data from a mongodb database and trying to pass that response to a front-end reactjs application.我正在尝试从mongodb数据库中检索数据并尝试将该响应传递给前端reactjs应用程序。

But I get this error and I can't find why it is happening:但是我收到这个错误,我找不到它发生的原因:

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返回类型必须是字符串、字典、元组、响应实例或可调用的 WSGI,但它是一个列表

What I need is:我需要的是:

I need to retrieve all the mongodb documents and pass it into front-end application so I can map it using reactjs to show in a table.我需要检索所有 mongodb 文档并将其传递给前端应用程序,以便我可以使用 reactjs 将其映射到表格中。

And this is what I am trying, and this is giving me the error:这就是我正在尝试的,这给了我错误:

@app.route("/bemployees", methods=["GET"])
def retrieve_all_documents():
    client = pymongo.MongoClient(
        "<url>"
    )

    # database
    db = client.cdap

    # collection (table)
    collection = db.predicted_values

    documents_ = []

    for b in collection.find():

        documents_.append({'Age' :b['Age'] ,'DailyRate': b['DailyRate'],
                   'DistanceFromHome': b['DistanceFromHome'] , 'EnvironmentSatisfaction': b['EnvironmentSatisfaction'],
                   'HourlyRate':b['HourlyRate'],'JobInvolvement': b['JobInvolvement'],
                   'JobLevel': b['JobLevel'],'JobSatisfaction' :b['JobSatisfaction'],
                   'MonthlyIncome': b['MonthlyIncome'], 'MonthlyRate' :b['MonthlyRate'],
                   'NumCompaniesWorked': b['NumCompaniesWorked'],'PercentSalaryHike' :b['PercentSalaryHike'],
                   'RelationshipSatisfaction': b['RelationshipSatisfaction'],'StandardHours' :b['StandardHours'],
                   'TotalWorkingYears': b['TotalWorkingYears'],'TrainingTimesLastYear' :b['TrainingTimesLastYear'],
                   'YearsAtCompany': b['YearsAtCompany'],'YearsInCurrentRole' :b['YearsInCurrentRole'],
                   'YearsSinceLastPromotion': b['YearsSinceLastPromotion'],'YearsWithCurrManager' :b['YearsWithCurrManager'],
                   'MaritalStatus_': b['MaritalStatus_'],'JobRole_' :b['JobRole_'],
                   'Gender_': b['Gender_'],'EducationField_' :b['EducationField_'],
                   'Department_': b['Department_'],'BusinessTravel_' :b['BusinessTravel_'],
                   'OverTime_': b['OverTime_'],'Over18_' :b['Over18_'],
                   'empName': b['empName'],'empID' :b['empID'],
                   'PerformanceScore': b['PerformanceScore'],
                   'id': str(b['_id']) })

    return documents_ 

Can someone please help me to fix this?有人可以帮我解决这个问题吗?

Flask views can't return lists. Flask 视图不能返回列表。 One way to deal with this is to convert your list to a JSON string:解决此问题的一种方法是将您的列表转换为 JSON 字符串:

import json
from flask import Response

@app.route("/bemployees", methods=["GET"])
def retrieve_all_documents():
    client = pymongo.MongoClient(
        "<url>"
    )

    # database
    db = client.cdap

    # collection (table)
    collection = db.predicted_values

    documents_ = []

    for b in collection.find():

        documents_.append({'Age' :b['Age'] ,'DailyRate': b['DailyRate'],
                   'DistanceFromHome': b['DistanceFromHome'] , 'EnvironmentSatisfaction': b['EnvironmentSatisfaction'],
                   'HourlyRate':b['HourlyRate'],'JobInvolvement': b['JobInvolvement'],
                   'JobLevel': b['JobLevel'],'JobSatisfaction' :b['JobSatisfaction'],
                   'MonthlyIncome': b['MonthlyIncome'], 'MonthlyRate' :b['MonthlyRate'],
                   'NumCompaniesWorked': b['NumCompaniesWorked'],'PercentSalaryHike' :b['PercentSalaryHike'],
                   'RelationshipSatisfaction': b['RelationshipSatisfaction'],'StandardHours' :b['StandardHours'],
                   'TotalWorkingYears': b['TotalWorkingYears'],'TrainingTimesLastYear' :b['TrainingTimesLastYear'],
                   'YearsAtCompany': b['YearsAtCompany'],'YearsInCurrentRole' :b['YearsInCurrentRole'],
                   'YearsSinceLastPromotion': b['YearsSinceLastPromotion'],'YearsWithCurrManager' :b['YearsWithCurrManager'],
                   'MaritalStatus_': b['MaritalStatus_'],'JobRole_' :b['JobRole_'],
                   'Gender_': b['Gender_'],'EducationField_' :b['EducationField_'],
                   'Department_': b['Department_'],'BusinessTravel_' :b['BusinessTravel_'],
                   'OverTime_': b['OverTime_'],'Over18_' :b['Over18_'],
                   'empName': b['empName'],'empID' :b['empID'],
                   'PerformanceScore': b['PerformanceScore'],
                   'id': str(b['_id']) })

    return Response(json.dumps(documents_), mimetype='application/json')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flask返回TypeError:视图函数未返回有效响应 - Flask is returning TypeError: The view function did not return a valid response Flask REST API错误:视图函数未返回有效响应 - Flask REST API Error: The view function did not return a valid response 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 in flask 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" Python Flask未针对MySQL请求返回有效响应 - Python Flask did not return a valid response for MySQL request 类型错误:视图 function 未返回有效响应。 返回类型必须是字符串、字典、元组、Response 实例,但它是一个 int - TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, but it was a int
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM