[Python] Unhandled exception: Connection timed out | Flutter | REST API

Discussão em 'Python' iniciado por Stack, Fevereiro 4, 2025.

  1. Stack

    Stack Membro Participativo

    I have built a REST API using Flask framework in Python and it works completely fine when tested via Postman. But when I make requests using an android emulator, I get an exception displaying "Connection timed out".

    I am aware that the localhost for android emulator is 10.0.2.2:8000 and not 127.0.0.1:5000, and I am making the request accordingly. But I have still no luck in receiving the response that I want.

    API code:

    from collections import defaultdict
    from flask import Flask, request, jsonify

    app = Flask(__name__)

    @app.route("/")
    def home():
    return {"message": "Hello and Welcome"}


    @app.route("/getkeywords", methods=["POST"])
    def getKeywords():
    res = request.get_json()

    text = res["text"]
    data = extractKeywords(text)
    # print(text)

    return jsonify({"data": data})


    from rake_nltk import Rake

    def extractKeywords(text: str):
    r = Rake()
    r.extract_keywords_from_text(text)
    data = defaultdict(list)
    for rating, keyword in r.get_ranked_phrases_with_scores():
    data[rating].append(keyword)

    return data


    if __name__ == "__main__":
    app.run(debug=True)



    Flutter code:

    Future<void> getKeywords(String text) async {
    String mainURL = "http://10.0.2.2:8000/getkeywords";

    final response = await http.post(Uri.parse(mainURL), body: {"text": text});
    if (response.statusCode == 200) {
    print(response.body);
    } else {
    throw Exception("Failed to get data");
    }
    }


    Debug console output: [​IMG]

    Continue reading...

Compartilhe esta Página