为什么 flutter post 请求到 fastapi 服务器返回“连接超时”错误?

问题描述 投票:0回答:0

我正在尝试使用 fastapi 服务从我的 flutter 应用程序中输入的文本中获取情绪。 这是 fastapi.it 在我使用 swagger 实用程序时工作的代码。 这是带有 post 请求的 fastapi 服务器的代码片段:



@app.post('/predict')
def predict_sentiment(data: SentimentData):
    data = data.dict()
    print(data)
    text = data['text']
    output = predict(vectoriser, LRmodel, text)
    if (output == 1):
        prediction = "positive"
    else:
        prediction = "negative"
    return prediction


这是上面代码中的“SentimentData”:


from pydantic import BaseModel


class SentimentData(BaseModel):
    text: str

这是应用程序处理发布请求的部分:

RoundButton(
                        title: 'detect sentiment',
                        onPress: () async {
                          var url = Uri.parse('http://10.0.2.2:8000/predict');
                          var data = {
                            'text': descriptionController.text.toString()
                          };
                          var body = json.encode(data);
                          print(body);
                          print("the ends");
                          var headers = {
                            'Content-Type': 'application/json',
                          };

                          // Send the POST request
                          var response = await http.post(url,
                              headers: headers, body: body);
                          print(response.statusCode);
                          // Handle the response
                          if (response.statusCode == 200) {
                            var result = response.body;
                            print(result);
                            sentiment = result;
                            // Process the result
                          } else {
                            print(
                                'Request failed with status: ${response.statusCode}');
                          }
                        }),

这是上面代码中修改的“sentiment”变量

  TextEditingController descriptionController = TextEditingController();
  String sentiment = "";

这是控制台输出:

I/ViewRootImpl@14bc534MainActivity: ViewPostIme 指针 0 I/ViewRootImpl@14bc534MainActivity: ViewPostIme 指针 1 I/flutter (30724): {"text":"this is a sad post"} I/flutter (30724): 结束 E/flutter (30724): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] 未处理的异常:连接超时 E/flutter (30724): #0 IOClient.send (包:http/src/io_client.dart:94:7) E/颤动(30724): E/flutter (30724): #1 BaseClient._sendUnstreamed (包:http/src/base_client.dart:93:32) E/颤动(30724): E/flutter (30724): #2 _withClient (包:http/http.dart:166:12) E/颤动(30724): E/颤振 (30724):#3 _AddPostScreenState.build。 (包:project_phase_one/screens/add_post.dart:95:42) E/颤动(30724): E/颤动(30724):

我正在尝试在“descriptionController”中获取用户输入文本中的情绪,将其发送到快速 api 服务器并将情绪作为“消极”或“积极”的变量“情绪”。

android flutter firebase http-post fastapi
© www.soinside.com 2019 - 2024. All rights reserved.