【问题标题】:flask - Display database from python to htmlflask - 显示从 python 到 html 的数据库
【发布时间】:2017-08-08 02:25:45
【问题描述】:

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

【问题讨论】:

    标签: python html web flask server


    【解决方案1】:

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

    【讨论】:

    • 嗨,David,您能否提供完整的代码来从数据库中提取数据,尤其是如何将它们推送到 html?
    【解决方案2】:

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

    中发送

    示例

    app.py

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

    test.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,请查看他的 Documentation

    【讨论】:

    • 但是我会从数据库中加载 1000 条数据。
    • 那么你需要使用一些分页技术,这是一个设计问题,而不是使用的技术
    • @DavidHerlianto 对于分页,您可以尝试在代码中将cur.fetchall() 替换为cur.fetchmany(20),以测试当限制为每页20 个项目时您的第一页会是什么样子。显示以下页面只需为您的请求传递所选页面的参数,并相应地滚动光标。
    【解决方案3】:

    假设您有 table_name = user_info,让我们将其可视化:

    身份证|姓名 |电子邮件 |电话 | 1 |埃尔塔克 | eltac@gmail.com | +99421112 |


    你可以这样做:

    app_name.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)
    
    
    

    在上面的代码中,我们使用了 fetchall() 方法,这就是为什么 ID 也会自动包含在内的原因

    (标题 html 标记和其他标记被忽略。我只写在正文内部) 例子.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--
    
    
    

    最后你得到了预期的结果

    【讨论】:

      猜你喜欢
      • 2018-01-15
      • 2020-03-05
      • 1970-01-01
      • 2020-05-09
      • 2020-04-11
      • 2020-09-20
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      相关资源
      最近更新 更多