【发布时间】:2020-10-12 12:22:47
【问题描述】:
我正在尝试与我的机器学习模型进行交互,在该模型中我可以从 HTML 获取烧瓶路由方法的输入值,但无法将带有字符串值的响应传递给 ajax 查询。
单击按钮会命中 ajax 函数并确实转到了烧瓶路由函数,但它甚至没有命中 ajax 函数的成功或错误部分。 给出 405 Method not Allowed 错误。 127.0.0.1 - - [12/Oct/2020 13:15:17] “POST / HTTP/1.1”405 -
我是 Flask 新手,不知道数据绑定选项。任何帮助将不胜感激。
HTML 部分
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="{{ url_for('static',
filename='css/bootstrap.min.css') }}">
<title>Twitter Sarcasm Detection</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<script src="static/js/signUp.js"></script>
<style>
h1 {
margin-top: 13rem;
color: chocolate
}
p{
margin-top: 36px;
}
.form-group{
margin: 3rem !important;
}
</style>
</head>
<body>
<div class="container" style="text-align:center">
<h1>Twitter Sarcasm Detection</h1>
<p>Enter the text below to find out if its Sarcastic or not!</p>
<form action="http://localhost:5000/" method="post">
<div class="form-group">
<input type="text" class="form-control" id="userText" name="userText">
</div>
<button id="submit" class="btn btn-primary">Submit</button>
<input type="reset" value="Reset" class="btn btn-primary">
<div class="form-group">
<label id="prediction" name="prediction"></label>
</div>
</form>
</div>
脚本文件中的 AJAX 查询
$(function(){
$('#submit').click(function(){
$.ajax({
url: '/predictSarcasm',
data: $('form').serialize(),
type: 'POST',
success: function(response){
$('#prediction').val(response.result);
},
error: function(error){
console.log(error);
}
});
});
});
烧瓶代码
from flask import Flask, render_template, json
from joblib import load
pipeline = load("text_classification.joblib")
def requestResults(text):
tweet = pipeline.predict([text])
if tweet == 0:
return "Not-Sarcastic"
else:
return "Sarcastic"
app = Flask(__name__)
@app.route("/")
def home():
return render_template('Index.html')
@app.route('/predictSarcasm', methods=['POST'])
def predictSarcasm():
text = request.form['userText']
prediction = requestResults(text)
return json.dumps({'status':'OK','result':str(prediction)});
if __name__ == "__main__":
app.run(debug=False)
【问题讨论】:
标签: python flask data-binding