我有这样的代码从数据库中检索数据,我想以html显示。
这是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')
这是结果
这是berita.html。我想显示在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>
你可以使用以下方式传递数据render_template()
:
cur = con.cursor()
cur.execute("SELECT * FROM dataset")
data = cur.fetchall()
render_template('template.html', data=data)
然后在模板中,对行进行迭代,例如,可以为每一行呈现表行:
{% for item in data %}
<tr>
<td>{{item[0]}}</td>
<td>{{item[1]}}</td>
...
</tr>
{% endfor %}
嗨,大卫,您能否提供完整的代码,从数据库中提取数据,尤其是如何将其推送到html?