Home  >  Q&A  >  body text

The data was successfully stored in server.py, but a 404 not found error occurred when trying to retrieve it.

I wrote a server.py file that can save students' names, index numbers and average grades. When I run the client.html file and enter the data and click add student, it says the student was added successfully, but when I enter his index to use the get students function, it says 404 Student Not Found.

This is the server.py file code:

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)

This is the client.html file code:

<!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>

P粉668019339P粉668019339240 days ago396

reply all(1)I'll reply

  • P粉300541798

    P粉3005417982024-02-22 13:35:20

    In the html page you have given the same id to both elements (index set box and get box) so the code is only looking for the first element so the index in the dictionary will be equal to " " and the code cannot find it it.

    EDIT: Another mistake is that the index must be a string, in the get function it must be a string. [Just execute index = str(index)]

    Hope it helps.

    reply
    0
  • Cancelreply