NameD = request.form('Name') TypeError: 'ImmutableMultiDict' object is not callable

NameD = request.form('Name') TypeError: 'ImmutableMultiDict' object is not callable

我想将这些值传递给我的 Flask 并接收响应。 这就是我如何构建我的 FormBody 和请求以及恢复其响应的方法:

OkHttpClient okHttpClient;
RequestBody formBody;
Request request;

okHttpClient= new OkHttpClient();
formBody=new FormBody.Builder().add("Name",Date_Time).add("Humidity_value",hum).build();

request=new Request.Builder().url("http://10.0.2.2:5000/api").post(formBody).build();

okHttpClient.newCall(request).enqueue(new Callback() {
 @Override
 public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("message","Network not found");
            }

 @Override
 public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.d("message",response.body().string());
            }
        });

我放置了依赖项并导入了所需的库,但在 Android Studio 中出现错误:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <title>500 Internal Server Error</title>
    <h1>Internal Server Error</h1>
    <p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

我的烧瓶端还有一个错误:

Name = request.form('Name')
TypeError: 'ImmutableMultiDict' object is not callable
127.0.0.1 - - [27/Mar/2021 15:12:01] "POST /api HTTP/1.1" 500 -

这是我的烧瓶代码:


@app.route('/api', methods=['POST'])
def predict():
    NameD = request.form('Name') **#the console said the error is here**
    NameD = pd.to_datetime(NameD).value
    NameD = float(NameD)
    Humidity_value = request.form('Humidity_value')
   
    
    inputs = np.array([[NameD,Humidity_value]])

    prediction = model.predict(inputs)
    output = prediction[0]
    
    return (str(output))


if __name__ == "__main__":
    app.run(host="0.0.0.0")

如何解决 TypeError: 'ImmutableMultiDict' object is not callable 错误?

request.form 是一个 ImmutableMultiDict 类似于 python 字典,您不能使用 round brackets () 从表单中检索数据。而是使用 square brackets []。将 request.form('key') 的所有实例更改为 request.form['key']。或者您可以使用 request.form.get('key').

这里使用圆括号 () 类似于尝试调用函数。由于我们无法调用 ImmutableMultiDict,因此发生了错误。 android工作室内部的错误很可能是因为flask脚本中的错误。

你的预测函数应该是

@app.route('/api', methods=['POST'])
def predict():
    NameD = request.form['Name']
    NameD = pd.to_datetime(NameD).value
    NameD = float(NameD)
    Humidity_value = request.form['Humidity_value']
    Light_Sensor_Reading = request.form['Light_Sensor_Reading']
    Smoke_Detection = request.form['Smoke_Detection']
    Temperature_value = request.form['Temperature_value']
    Door_status = request.form['Door_status']
    
    inputs = np.array([[NameD,Humidity_value,Light_Sensor_Reading,Smoke_Detection,Temperature_value,Door_status]])

    prediction = model.predict(inputs)
    output = prediction[0]
    
    return (str(output))