I have code like this to retrieve data from database and I want to display it in html.
This is app.py
@app.route('/news')
def news():
import pymysql
import re
host='localhost'
user = 'root'
password = ''
db = 'skripsi'
try:
con = pymysql.connect(host=host,user=user,password=password,db=db, use_unicode=True, charset='utf8')
print('+=========================+')
print('| CONNECTED TO DATABASE |')
print('+=========================+')
except Exception as e:
sys.exit('error',e)
cur = con.cursor()
cur.execute("SELECT * FROM dataset")
data = cur.fetchall()
for row in data:
id_berita = row[0]
judul = row[1]
isi = row[2]
print('===============================================')
print('BERITA KE', id_berita)
print('Judul :', judul)
print('Isi :', isi)
print('===============================================')
return render_template('home.html')
This is the result
This is berita.html. I want to display inside div class = output
<body>
<center>
<header style="padding-top: 10px; font-family: Calibri; font-size: 40pt;">WELCOME!</header><br>
<div class="nav">
<a href="/home">Home
<a href="/berita">Berita
<a href="/preprocessing">Pre-Processing
<a href="/feature">Fitur Ekstraksi
<a href="/knn">KNN
</div>
<div class="output">
</div>
Create a simple HTML page to display text. create a route ”/” and return home. html from the function. Then run your api.py file and click on the link that it provides after running.
import mysql. connector import webbrowser conn = mysql. connector. connect(user='root', password='', host='localhost',database='company') if conn: print ("Connected Successfully") else: print ("Connection Not Established") select_employee = """SELECT * FROM employee""" cursor = conn.
render_template allows you to pass variables to html, and jinja2 help you to manipulate it. You only need to format your query result and send it within render_template
@app.route('/test')
def test_route():
user_details = {
'name': 'John',
'email': '[email protected]'
}
return render_template('test.html', user=user_details)
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<!-- use {{}} to access the render_template vars-->
<p>{{user.name}}</p>
<p>{{user.email}}</p>
</body>
</html>
to make the most of jinja2, take a look at his Documentation
You can pass your data using render_template()
like this:
cur = con.cursor()
cur.execute("SELECT * FROM dataset")
data = cur.fetchall()
render_template('template.html', data=data)
Then in your template, iterate over the rows, for example you could render table rows for each row:
{% for item in data %}
<tr>
<td>{{item[0]}}</td>
<td>{{item[1]}}</td>
...
</tr>
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With