简体   繁体   English

如果通过 client.html 将数据存储在 server.py 中,它说我成功了,但是当我尝试检索它时,它说 404 not found

[英]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.

相关问题 Angular $scope 对象显示 $scope.data 但当我尝试使用它时,显示未定义 - Angular $scope object showing $scope.data but when I try to use it, the says undefined 我在rss feed上收到错误消息,提示未找到数据 - I receive error message on my rss feed says no data was found 添加时的Chrome扩展程序本地化问题-说我没有指定默认语言环境 - Chrome Extension localization issue when adding it — says i didnt specify default locale even though i did 使用node.js和socket.io时,为什么我不能只打开client.html文件而不是在地址栏中键入localhost? - When using node.js and socket.io, why can't I just open the client.html file instead of typing localhost in the address bar? 如何通过添加for循环来遍历data.games并在搜索中显示比分时也进行添加来重写搜索功能? - How do I rewrite the search function by adding a for loop to go through data.games and also add when I search that it says the score? 当我尝试使用ajax时,chrome的控制台显示“资源加载失败” - When I try to use ajax, chrome's console says “”Resource failed to load" 每当我尝试启动我的 discord 机器人时,我都会收到一条错误消息,它显示 ReferenceError: client is not defined,因此我的机器人不会启动 - I get a error message whenever I try and start my discord bot it says ReferenceError: client is not defined, and my bot wont start because of that 为什么我的模态框会弹出一条消息,当我尝试使用基于我单击的数据填充它时,显示传入的对象无效 - Why does my modal box pop up with a message that says invalid object passed in when I try populate it with data based on what I have clicked 当我尝试执行 ParentNode.children 时,显示无法读取未定义的属性“子项” - When I try to do ParentNode.children, says Cannot read property 'children' of undefined 当我尝试访问快递路线时未找到404错误 - Not Found 404 Error when i try to access an express route
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM