0

This is the "apprunner.py" of my flask

   from flask import *
   from flaskext.mysql import MySQL

   enter code hereapp = Flask(__name__)


   mysql = MySQL()
   app.config['MYSQL_DATABASE_USER'] = 'root'
   app.config['MYSQL_DATABASE_PASSWORD'] = 'myPassword'
   app.config['MYSQL_DATABASE_DB'] = 'myDB'
   app.config['MYSQL_DATABASE_HOST'] = 'localhost'
   mysql.init_app(app)



  conn = mysql.connect()
  cursor =conn.cursor()

  cursor.execute("SELECT * from clients")
  data = cursor.fetchall()



 @app.route("/")
 def index():
   return render_template("index.html")

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

and this is my index.html file:

 <!DOCTYPE html>
     <head>
         <!-- some code here-->
     </head>
     <body>
         <div id='info_section'>
         </div>
     </body>
 </html>

In the data variable in the "apprunner.py" file, it contains all the entries of the "clients" table as a form of tuples. What I want to do is load the clients info from the clients table into the block in the html file whose id is "info_section". How can achieve it in python?

1
  • Refer Jinja templating . You need to pass your data to you template i.e index.html as argument. in this way render_template('index.html',data)...In your html page write templating. Commented Jun 14, 2018 at 18:36

1 Answer 1

2

You need to pass the data to the template like so.

return render_template("index.html", data=data)

Then in the HTML file you can loop through the data like this.

<div id='info_section'>
    {% for data in data %}
        <p>{{ data }}</p>
    {% endfor %}
</div>

If you want to access a column of the entry you can do <p>{{ data.whatever_attribute }}</p>

Sign up to request clarification or add additional context in comments.

3 Comments

This is a good start. But, all it does is to load the data sequentially from for loop. However, if I want to enhance the loop. Let's say I want to display this element and the next element in one loop cycle. How am I supposed to do it?
As in having two different objects or having two different attributes?
For example, the data variable in python is a list. ['apple','banana','cheese']. Now, I want to process 'apple' and 'banana' in the same loop cycle in the html inside the <div>. Am I able to do it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.