flask - 从 python 到 html 显示数据库

新手上路,请多包涵

我有这样的代码从数据库中检索数据,我想用 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>

原文由 David Herlianto 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 416
2 个回答

您可以使用 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 %}

原文由 bgse 发布,翻译遵循 CC BY-SA 3.0 许可协议

render_template 允许您将变量传递给 html,而 jinja2 帮助您对其进行操作。您只需要格式化您的查询结果并在 render_template 中发送它

例子

应用程序.py

 @app.route('/test')
def test_route():
    user_details = {
        'name': 'John',
        'email': 'john@doe.com'
    }

    return render_template('test.html', user=user_details)

测试.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>

要充分利用 jinja2,请查看他的 文档

原文由 DobleL 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题