vendredi 10 avril 2015

Python: Simple display data from database web app

Here is the python method which displays the student's data



@app.route('/displayStudent', methods =['GET'])
def displayStudent():
residence = request.args['residence']
try:
conn = None
conn = getConn()
cur = conn.cursor()
cur.execute('SET search_path to public')

cur.execute('SELECT stu_id,student.name,course.name,home_town FROM student,\
course WHERE course = course_id AND student.residence = %s',[residence])
rows = cur.fetchall()
if rows:
return render_template('stu.html', rows = rows, residence = residence)
else:
return render_template('index.html', msg1='no data found')

except Exception as e:
return render_template('index.html', msg1='No data found', error1 = e)

finally:
if conn:
conn.close()


Here is the html form



<h1> Welcome to the student database</h1>
</h3> Display student data by residence</h3>
<form action = "displayStudent" method ="get">
Residence Name = <input type = "text" name = "residence"><br>
<input type = "submit" value = "Proceed to list">
</form>
{{msg1}}<br>
{{error1}}


And here is the output page



<!DOCTYPE html>
<html>
<body<
<h1> Student Data for {{residence}} </h1>

<table border = 1>
<tr>
<th>ID</th <th>Name</th> <th> Course</th> <th> Home Town</th>
</tr>
{% for row in rows %}
<tr>
{%for item in row%}
<td>
{{item}}
</td>
{%endfor%}
</tr>
{%endfor%}
</table>
<form action ="/">
<input type="submit" value ="Home">
</form>
</body>
</html>


Can't quite figure out the problem here. I know I'm probably missing something very simple but it's really frustrating me, i've rewritten the code multiple times. Also how would I get around problems like this in the future.


Aucun commentaire:

Enregistrer un commentaire