Home > Enterprise >  If store data in server.py through client.html it says that I did it successfully, but when I try to
If store data in server.py through client.html it says that I did it successfully, but when I try to

Time:01-14

I wrote a server.py file that enables saving the name, surname, index number and average grade of the students. 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.

Here 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)

And here 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>

CodePudding user response:

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.

Edit: Another error is that the index must be a string, in the get function must be a string. [just do index = str(index)]

Hope thats help.

CodePudding user response:

The form fields from request.form are strings, therefore the dictionary key index is also a string. On lookup you should make sure that it is a string as well, instead of an int:

@app.route('/get_student/<string:index>', methods=['GET'])

Result:

enter image description here

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. Note that this should also be in a try-except block if you want to handle non-numeric input from the html page.

  • Related