[英]If store data in server.py through client.html it says that I did it successfully, but when I try to retrieve it, it says 404 not found
I wrote a server.py file that enables saving the name, surname, index number and average grade of the students.我写了一个 server.py 文件,可以保存学生的名字、姓氏、索引号和平均成绩。 When I run the client.html file and enter the data and click add student, it says that the student is successfully added, but when I enter his index in order to use the get student function, it says 404 student not found.
当我运行client.html文件并输入数据并点击添加学生时,它说学生已成功添加,但是当我输入他的索引以使用获取学生function时,它说找不到404学生。
Here is the server.py file code:这是 server.py 文件代码:
from flask import Flask, request, jsonify
import pickle
app = Flask(__name__)
try:
with open('students.pickle', 'rb') as f:
students = pickle.load(f)
except FileNotFoundError:
students = {}
@app.route("/")
def index():
with open("client.html") as f:
return f.read()
@app.route('/add_student', methods=['POST'])
def add_student():
name = request.form.get('name')
surname = request.form.get('surname')
index = request.form.get('index')
grade = request.form.get('grade')
students[index] = {'name': name, 'surname': surname, 'index': index,'grade': grade}
with open('students.pickle', 'wb') as f:
pickle.dump(students, f)
return jsonify(message='Student added successfully'), 201
@app.route('/get_student/<int:index>', methods=['GET'])
def get_student(index):
student = students.get(index)
if student:
return jsonify(student)
else:
return 'Student not found', 404
if __name__ == '__main__':
app.run(host='localhost', port=8000, debug=True)
And here is the client.html file code:这是 client.html 文件代码:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
function getStudent() {
var index = $("#index").val();
$.ajax({
type: "GET",
url: "http://localhost:8000/get_student/" + index,
success: function(data) {
$("#student-info").text(JSON.stringify(data));
},
error: function() {
$("#student-info").text("Student not found");
}
});
}
function addStudent() {
var data = new FormData();
data.append("name", $("#name").val());
data.append("surname", $("#surname").val());
data.append("index", $("#index").val());
data.append("grade", $("#grade").val());
$.ajax({
type: "POST",
url: "http://localhost:8000/add_student",
data: data,
processData: false,
contentType: false,
success: function(data) {
$("#add-student-result").text("Student added");
},
error: function() {
$("#add-student-result").text("Error adding student");
}
});
}
$("#get-student-form").submit(function(e) {
e.preventDefault();
getStudent();
});
$("#add-student-form").submit(function(e) {
e.preventDefault();
addStudent();
});
});
</script>
</head>
<body>
<form id="get-student-form">
<label for="index">Index:</label>
<input type="text" id="index" name="index">
<button type="submit">Get Student</button>
</form>
<div id="student-info"></div>
<br>
<form id="add-student-form">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br>
<label for="surname">Surname:</label>
<input type="text" id="surname" name="surname">
<br>
<label for="index">Index:</label>
<input type="text" id="index" name="index">
<br>
<label for="grade">Grade:</label>
<input type="text" id="grade" name="grade">
<br>
<button type="submit">Add Student</button>
</form>
<div id="add-student-result"></div>
</body>
</html>
In the html page you have given two elements the same id (the index set box and the get one) and because of this the code finds only the first one, because of this the index in the dictionary will be equal to "" and the code doesn't find it.在 html 页面中,您给了两个元素相同的 id(索引集框和获取框),因此代码只找到第一个,因此字典中的索引将等于“”,并且代码没有找到它。
Edit: Another error is that the index must be a string, in the get function must be a string.编辑:另一个错误是索引必须是一个字符串,在get function 中必须是一个字符串。 [just do index = str(index)]
[只需做 index = str(index)]
Hope thats help.希望那是帮助。
The form fields from request.form
are strings, therefore the dictionary key index
is also a string. request.form
中的表单字段是字符串,因此字典键index
也是一个字符串。 On lookup you should make sure that it is a string as well, instead of an int:在查找时,您应该确保它也是一个字符串,而不是一个 int:
@app.route('/get_student/<string:index>', methods=['GET'])
Result:结果:
Alternatively you can convert the index to int before you store it in the dictionary (using index = int(request.form.get('index'))
) and then use <int:index>
in the route, in case you prefer the index to be an int.或者,您可以在将索引存储在字典中之前将其转换为 int(使用
index = int(request.form.get('index'))
),然后在路由中使用<int:index>
,以防您更喜欢索引是一个整数。 Note that this should also be in a try
- except
block if you want to handle non-numeric input from the html page.请注意,如果要处理来自 html 页面的非数字输入,这也应该在
try
- except
块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.