Home > Courses > Flask: Python Web Development > Fetch record from a database in Python/Flask

Fetch record from a database in Python/Flask

Subject: Flask: Python Web Development
As we continue from the previous lesson, after inserting data into the student table via the web form it is obvious that we will need to have a way to retrieve or access the data in flask rather than a third party tool.

We will use the SQL statement SELECT * FROM table (i.e Select all fields from table)

Step 1.
Create a template to view the record i.e seestudents.html in the templates folder as usual. And make it have the code below:

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

<body>
<h2>School Grading System</h2>
<hr/>
<a href="/student">Students</a> |
<a href="#">Subjects</a> |
<a href="#">Instructor</a> |
<a href="#">Score Sheet</a>
<hr/>
<h2>See Student Record</h2>

<a href="/">Back to home</a><br/>

<table width="100%" border=1>
<tr>
<th>Id</th>
<th>Surname</th>
<th>Othernames</th>
<th>Address</th>
</tr>
{%for rec in students%}
<tr>
<td>{{rec[0]}}</td>
<td>{{rec[1]}}</td>
<td>{{rec[2]}}</td>
<td>{{rec[3]}}</td>
</tr>
{%endfor%}
</table>
</body>
</html>


Step 2.
Update the app.py files as follows...


from flask import Flask, render_template, request
import sqlite3, os
app = Flask(__name__)

#get the current path name our app
dir_path = os.path.dirname(os.path.realpath(__file__))

#create and connect to the database in our current folder
conn = sqlite3.connect(dir_path+'/tealearn_grades.db', check_same_thread=False)


#.....

#view students record
@app.route('/seestudents')
def seestudents():
cursor = conn.cursor()
cursor.execute('SELECT * FROM student')
data = cursor.fetchall()
return render_template('seestudents.html', students=data)

#.....

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


Step 3.
Run the app.py file and access the route:
http://localhost:5000/seestudents


By: Benjamin Onuorah

Comments

No Comment yet!

Login to comment or ask question on this topic


Previous Topic Next Topic