flask-显示从python到html的数据库 [英] flask - Display database from python to html
本文介绍了flask-显示从python到html的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的代码可以从数据库中检索数据,并且我想以html显示.
I have code like this to retrieve data from database and I want to display it in 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里面显示
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>
推荐答案
您可以使用render_template()
这样传递数据:
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 %}
这篇关于flask-显示从python到html的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文