У меня проблемы с переносом простых данных и html-страницы в базу данных MySQL
я получаю сообщение об ошибке:
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'matchID'
Это код Python, который я использую для его отправкив базу данных MySQL
import mysql.connector as conn
from flask import (
render_template,
Flask,
jsonify,
request,
abort as ab
)
app = Flask(__name__)
def conn_db():
return conn.connect(user='***********',
password='***********',
host='***********',
database='**********'
)
@app.route('/')
def index():
return render_template('scores.html')
@app.route('/addScore', methods=['POST'])
def add_score():
cnx = conn_db()
cursor = cnx.cursor()
MatchID = request.form['matchID']
Home_Score = request.form['homeScore']
Away_Score = request.form['awayScore']
print("Updating score")
if not request.json:
ab(400)
cursor.execute("INSERT INTO scores (Match_ID, Home_Score, Away_Score) VALUES (%s,%s,%s,%s)",
(MatchID, Home_Score, Away_Score))
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
И это HTML-код с AJAX, который я использую
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<h1>Scores</h1>
<form method="POST">
<label>Match ID :</label>
<input id="matchID" name="matchID" required type="number"><br>
<label>Home Score:</label>
<input id="homeScore" name="homeScore" required type="number"><br>
<label>Away Score:</label>
<input id="awayScore" name="awayScore" required type="number"><br>
</form>
<button id="addScoreButton">Add score</button>
<button id="retrieveScoreButton">Retrieve all scores</button>
<br>
<div id="Scores">
<ul id="scoresList">
</ul>
</div>
<script>
$(document).ready(function () {
var matchID = $('#matchID').val();
var homeScore = $('#homeScore').val();
var awayScore = $('#awayScore').val();
$("#addScoreButton").click(function () {
$.ajax({
type: 'POST',
data: {MatchID: matchID, Home_Score: homeScore, Away_Score: awayScore},
url: "/addScore",
success: added,
error: showError
}
);
}
);
}
);
$(document).ready(function () {
$("#retrieveScoreButton").click(function () {
console.log(id);
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: showScores,
error: showError
}
);
}
);
}
);
function showScores(responseData) {
$.each(responseData.matches, function (scores) {
$("#scoresList").append("<li type='square'>" +
"ScoreID: " + scores.Score_ID +
"Match Number: " + scores.Match_ID +
"Home: " + scores.Home_Score +
"Away: " + scores.Away_Score
);
$("#scoresList").append("</li>");
}
);
}
function added() {
alert("Added to db");
}
function showError() {
alert("failure");
}
</script>
</body>
</html>
Любая помощь очень ценится,
Я включилsql для созданной таблицы результатов, в которую я добавляю, см. ниже
CREATE TABLE Scores
(Score_ID
int NOT NULL AUTO_INCREMENT, Match_ID
int NOT NULL, Home_Score
int NOT NULL, Away_Score
int NOT NULL, ПЕРВИЧНЫЙ КЛЮЧ (Score_ID
));