我在本地有一个python应用程序,我正试图用flask在我的网页上与之交互。我该怎么做?

2024-04-26 08:13:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我的html页面上有一个聊天框,它使用js让用户键入消息并与聊天机器人“交谈”。我将聊天机器人保存在本地存储的文件中。我试图用用户输入的数据调用聊天机器人的函数。我对Flask比较陌生,刚刚开始学习API。我是否需要从html文件同时执行get和post操作?以下是我的网页代码:

@app.route("/therapist", methods=['GET', 'POST'])
def therapist():
    def therapist_chat():
        userText = request.args.get('msg')
        return chat(userText)
    return render_template("therapist.html")

以下是我的html表单数据,其中也包含js:

<div id="userInput">
              <input id="textInput" class="form-control" type="text" name="msg" placeholder="Type Your Message Here">
              <input id="buttonInput" class="btn btn-success form-control" type="submit" value="Send">
          </div>
      </div>
    </div>

  <script>
    function getResponse() {
        let userText = $("#textInput").val();
        let userHtml = '<p class="userText"><span>' + userText + '</span></p>';
        $("#textInput").val("");
        $("#chatbox").append(userHtml);
        document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
        $.get("/get", { msg: userText }).done(function(data) {
        var botHtml = '<p class="botText"><span>' + data + '</span></p>';
        $("#chatbox").append(botHtml);
        document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
});
}
    $("#textInput").keypress(function(e) {
    //if enter key is pressed
        if(e.which == 13) {
            getResponse();
        }
    });
    $("#buttonInput").click(function() {
        getResponse();
    });
    </script>

下面是我的聊天机器人python文件函数:

def chat(str):
    while True:
        inp = input("You: ")
        if inp.lower() == "quit":
            break
        # uses the model to predict the best response from inp after bag of words is created for inp
        results = model.predict([bag_of_words(inp, words)])[0]
        # sort the prediction by most likely, finds the index with the largest number
        results_index = np.argmax(results)
        # then go thru and assign the probability to the actual tag
        tag = labels[results_index]
        # sets an error threshold that probability must be higher to output a response
        if results[results_index] > 0.7:
            # then looks at tag and choices a random response
            for tg in data["intents"]:
                if tg["tag"] == tag:
                    responses = tg["responses"]
            # prints the response
            print(random.choice(responses))
        else:
            noresponses = ["Why's that?", "Can you tell me more?", "Can you please elaborate?",
                           "We're here to try and help you, so can you please just tell us what is going on?"]
            print(random.choice(noresponses))

api路由真的把我搞砸了


1条回答
网友
1楼 · 发布于 2024-04-26 08:13:06

我能想到的最简单的解决方法就是解决这个问题:

@app.route("/therapist", methods=['GET', 'POST'])
def therapist():
    def therapist_chat():
        userText = request.args.get('msg')
        return chat(userText)
    return render_template("therapist.html")

进入:

@app.route("/therapist", methods=['GET'])
def therapist():
    userText = request.args.get('msg')
    return chat(userText)

基本上,我在这里所做的是,当用户输入某个内容时,将调用GET请求,它将返回聊天机器人生成的文本

但是,您应该首先检查是否可以发送GET

**友好提示:

therapist老实说,对于一条路线来说,这是一个糟糕的选择。。这令人困惑

相关问题 更多 >