Python Flask Data Structure

Run this code and explain the data structure we used.

Tools:

Python and Flask

How to run Python Flask (thirdygayares.com)

Github

Medium.com or Hashnode.com


Project Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>Add Student</h1>
<form method="POST" action="/add">
<input type="text" name="name" placeholder="Input Student" required >
    <button type="submit">Add</button>
</form>
<br>
<br>


<table>
    <thead>
        <tr>
            <th>index</th>
           <th>Name</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    {% for index, student in students %}
        <tr>
            <td>{{index}}</td>
            <td>{{student}}</td>
            <td >

                <form method="POST" action="/edit_student/{{ index }}">
                    <input type="text" name="new_name" value="{{student}}" required/>
                    <button type="submit">Submit</button>


                <a href="/delete/{{student}}" >Delete With Student Name</a>
                <a href="/delete-with-index/{{index}}">Delete With Index</a>
                <a href="/select/{{student}}">Select Student</a>
                </form>

            </td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</body>
</html>

Import Flask Library

from flask import Flask, render_template, request, redirect, url_for;

app = Flask(__name__)

Student_name (List Data Structure)

student_name = ["Spongebob", "Jimmy Neutron", "Alice"]

Fetch Student List Function

@app.route('/')
def fetch_student_list():
    student_with_index = list(enumerate(student_name))
    return render_template('index.html', students = student_with_index)

Add Student Function

@app.route('/add', methods=['POST'])
def add_student():
    name = request.form.get('name')
    if name:
        student_name.append(name)
    return redirect(url_for('fetch_student_list'))

Delete Student with name Function

@app.route('/delete/<string:name>')
def delete_student(name):
    student_name.remove(name)
    return redirect(url_for('fetch_student_list'))

Delete Student with index function

@app.route('/delete-with-index/<int:index>')
def delete_student_with_index(index):
    student_name.pop(index)
    return redirect(url_for('fetch_student_list'))

Select Student

@app.route('/select/<string:name>')
def selected_student(name):
    print("selected " , name);
    return redirect(url_for('fetch_student_list'))

Edit STudent

@app.route('/edit_student/<int:index>', methods=['POST'])
def edit_student(index):
    new_name = request.form.get("new_name")
    student_name[index] = new_name
    return redirect(url_for('fetch_student_list'))

run

if __name__ == '__main__':
    app.run(debug=True)

python app.py

OUTPUT:

Updated on