flask - 从 python 到 html 显示数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45558349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
flask - Display database from python to html
提问by David Herlianto
I have code like this to retrieve data from database and I want to display it in html.
我有这样的代码来从数据库中检索数据,我想在 html 中显示它。
This is app.py
这是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
这是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>
回答by bgse
You can pass your data using render_template()
like this:
您可以使用render_template()
如下方式传递数据:
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 %}
回答by DobleL
render_templateallows you to pass variables to html, and jinja2help you to manipulate it. You only need to format your query result and send it within render_template
render_template允许你将变量传递给 html,jinja2帮你操作它。您只需要格式化查询结果并在render_template 中发送
Example
例子
app.py
应用程序
@app.route('/test')
def test_route():
user_details = {
'name': 'John',
'email': '[email protected]'
}
return render_template('test.html', user=user_details)
test.html
测试.html
<!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
要充分利用 jinja2,请查看他的文档
回答by Eltac Shikhsaidov
Suppose you have table_name = user_info and let's visualize it:
假设您有 table_name = user_info 并让我们对其进行可视化:
id| name | email | phone | 1 | Eltac | [email protected] | +99421112 |
身| 姓名 | 电子邮件 | 电话 | 1 | 艾尔泰克 | [email protected] | +99421112 |
You can do something like this:
你可以这样做:
app_name.py
应用名称.py
from flask import Flask, render_template
import mysql.connector
mydatabase = mysql.connector.connect(
host = 'localhost(or any other host)', user = 'name_of_user',
passwd = 'db_password', database = 'database_name')
mycursor = mydatabase.cursor()
#There you can add home page and others. It is completely depends on you
@app.route('/example.html')
def example():
mycursor.execute('SELECT * FROM user_info')
data = mycursor.fetchall()
return render_template('example.html', output_data = data)
In the above code we use fetchall() method that's why ID is also included automatically
在上面的代码中,我们使用了 fetchall() 方法,这就是为什么 ID 也被自动包含的原因
(Header html tag and others are ignored. I write only inside of body) example.html
(标题 html 标签和其他标签被忽略。我只写在正文内部)example.html
--snip--
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
{% for row in output_data %} <-- Using these '{%' and '%}' we can write our python code -->
<tr>
<td>{{row[0]}}</td>
<td>{{row[1]}}</td>
<td>{{row[2]}}</td>
<td>{{row[3]}}</td>
</tr>
{% endfor %} <-- Because it is flask framework there would be other keywords like 'endfor' -->
</tbody>
</table>
--snip--
And finally you get expected result
最后你得到了预期的结果