【问题标题】:Data from SQLITE to an HTML table in a Flask page从 SQLITE 到 Flask 页面中的 HTML 表的数据
【发布时间】:2019-01-13 18:51:36
【问题描述】:

我在 SQLite3 中有一个表,我需要获取表中几乎所有的列并将它们输出到网页。对于其他页面,我使用了 Flask,但总是将 3 或 4 个单值变量传递到模板中。

我猜这类似于将游标传递给模板,或者更可能的是,将来自 cursor.fetchall() 调用的行传递给模板,然后在模板中传递一个 for row in rows 循环?

【问题讨论】:

标签: python sqlite flask


【解决方案1】:

应该是:

<table>
{% for item in items %}
    <tr>
        <td>{{column1}}</td>
        <td>{{column2}}</td>
        <td>{{column3}}</td>
        <td>{{column4}}</td>
    </tr>
{% endfor %}
</table>

【讨论】:

    【解决方案2】:

    您需要遵循以下内容:

    [HTML]:

    <table>
    {% for item in items %}
    <tr>
        <td>{{item[0]}}</td>
        <td>{{item[1]}}</td>
        <td>{{item[2]}}</td>
        <td>{{item[3]}}</td>
    </td>
    {% endfor %}
    

    [python代码]:

    cursor = db.execute('SELECT column1,column2,column3,column4 FROM tablename')
    items = cursor.fetchall()
    return render_template('print_items.html', items=items)
    

    【讨论】:

      【解决方案3】:

      将您的数据作为某种集合传递,无论是像 the official tutorial 中的字典,还是更简单的东西,如元组或列表。

      是的,在您的模板中,您将使用{% for item in collection %} -&gt; {% endfor %} 循环来呈现数据库中的所有数据。

      示例 Python 方法:

      @app.route('/print_items')
      def print_items():
          cursor = db.execute('SELECT column1,column2,column3,column4 FROM tablename')
          return render_template('print_items.html', items=cursor.fetchall())
      

      示例模板部分:

      <table>
      {% for item in items %}
          <tr>
              <td>column1</td>
              <td>column2</td>
              <td>column3</td>
              <td>column4</td>
          </td>
      {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-13
        • 2020-04-11
        • 1970-01-01
        • 2020-12-02
        • 2021-04-20
        • 2010-11-30
        • 2020-05-09
        相关资源
        最近更新 更多