python - 如何使用 html 和烧瓶与聊天机器人聊天
问题描述
到目前为止,我已经为聊天机器人创建了后端,我只是试图让后端和前端(即网站)在它们之间进行通信。因此,我已经使前端能够发送消息,并且它将在具有对话历史记录的文本区域上进行更新。对于前端,这是我的 Html 文件 index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="serviceStyles.css">
<title>Team project</title>
</head>
<body>
<h1>Title n stuff</h1>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html">test link</a></li>
<li><a href="index.html">test link</a></li>
<li><a href="index.html">test link</a></li>
<li><a href="index.html">test link</a></li>
</ul>
</nav>
<h3 style='color: #ccc;font-size: 30px;'>No message yet..</h3>
<div class="message_holder"></div>
<form action="" method="POST">
<input type="text" class="input_msg" placeholder="Messages"/>
<input type="submit"/>
</form>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script type="text/javascript">
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on( 'connect', function() {
socket.emit( 'my event', {
data: 'User Connected'
} )
var form = $( 'form' ).on( 'submit', function( e ) {
e.preventDefault()
let user_input = $( 'input.input_msg' ).val()
socket.emit( 'my event', {
message : user_input
} )
$( 'input.input_msg' ).val( '' ).focus()
} )
} )
socket.on( 'my response', function( msg ) {
console.log( msg )
if( typeof msg.message !== 'undefined' ) {
$( 'h3' ).remove()
$( 'div.message_holder' ).append( '<div><b style="color: #000"></b> '+msg.message+'</div>' )
}
})
</script>
</body>
</html>
这是我的后端文件,我的 app.py,其中包含所有聊天机器人功能和烧瓶。
from flask import Flask, render_template, request
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/')
def session():
return render_template('index.html')
def messageReceived(methods=['GET', 'POST']):
print('message was received!!!')
@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
print('received my event: ' + str(json))
socketio.emit('my response', json, callback=messageReceived)
@app.route('/chat', methods=['POST'])
def chat():
print("Start talking with the bot! (type exit to stop)")
while True:
inp = input("You: ")
if inp.lower() == "exit":
break
results = model.predict([bag_of_words(inp, words)])[0]
results_index = numpy.argmax(results)
tag = labels[results_index]
if results[results_index] > 0.7:
for tg in data["intents"]:
if tg['tag'] == tag:
responses = tg['responses']
print(random.choice(responses))
else:
print("Sorry, I didnt quite understand what you typed, try asking a more specified question or another "
"questions.")
return render_template('index.html')
def chat_send():
text = request.form['user_inp']
x = text()
chat(x)
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app, debug=True)
目前,我无法将输入消息chat()
从 HTML 传递给函数,并且我也收到错误,例如Method Not Allowed The method is not allowed for the requested URL.
当我尝试访问http://127.0.0.1:5000/chat时,控制台会提示以下错误.OSError: [WinError 10038] An operation was attempted on something that is not a socket
解决方案
这是因为您的方法是发布的,但是当您使用 api 调用时,它应该被获取
代替
@app.route('/chat', methods=["POST"])
至
@app.route('/chat', methods=["GET", "POST"])
推荐阅读
- c# - 使用派生类的 C# 字典查找
- homebrew - 在调试模式下运行 tomcat 作为 brew 服务?
- android - 带有自定义指示器的选项卡布局
- c# - 如何将值发送到另一个视图
- javascript - 给定一个数组和正整数 d,有效地将数组左移 d
- image - 我需要 Opencart 3 上的 webp 图像。有可能吗?
- java - 线程“主”java.net.BindException 中的异常:地址已在使用中(绑定失败)
- html - 在元素的一部分上居中 Flexbox
- javascript - 如何在 React Native 中实现 Context API
- r - Rcpp eig_sym 和 R 的特征不提供相同的结果