JayRizla JayRizla - 1 year ago 63
HTML Question

Retrieve record from SQL database and print in HTML (via Python)

I am creating a single page web application using Flask's micro-framework.

I have SQL procedures implemented within the database to handle the log in and registration of users.

I am trying to retrieve the name of the user that has logged in and print a welcome message to that users profile page, upon login.

This is the python script so far, It is trying to retrieve all user_name(s) from tbl_user and print them to the userHome page.


def userHome():
if session.get('user'):
return render_template('userHome.html')

cursor1 = db.cursor()
cursor1.execute("select user_name from tbl_user")
result = cursor1.fetchall()
for row in result:
print (row[0])

return render_template('error.html',error = 'Unauthorized Access')


userHome.html (section in which I would like to print user's user_name)

<body style="border:1px solid blue;background:#ffffff;">

<div class="row" style="padding-right:20px;">

<!--PROFILE PIC Section-->
<div class="col-md-3 col-md-offset-1">
<div style="background:#f2f2f2;box-shadow: 10px 10px 30px #333333;margin-right:;">

<img class="" src="http://jnrgym.com/wp-content/uploads/2013/08/Facebook-no-profile-picture-icon-620x389.jpg" style="width:100%;max-height:100%;padding:5%;">

<p style="border:1px solid red;text-align:center;">

{user_name} << this is where I would like user_name to appear




I am aware that this is not the the correct method to achieve the desired outcome, however this is my first time ever using python. My question is how do I pass the result/output from my python script to my HTML page? (or at the very least print it to the chrome console )

Answer Source

You should make use of the Jinja template engine since the error.html file is using it already.

Inside your template for userHome.html you can add the following placeholder where ever you'd like the user name to appear

{{ userName }}

Then inside your app.py, use the following to pass the user name to the template

return render_template('userHome.html', userName = userName)

The variable userName should contain the string that you have fetched from your SQL database.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download