从SQLITE到Flask pag中的HTML表的数据

2024-09-30 14:27:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我猜这就像是把光标或者更可能是cursor.fetchall()调用中的行传递到模板中,然后在模板中循环一个for row in row s?


Tags: in模板webflaskfor页面sqlite3cursor
3条回答

您需要遵循以下步骤:

[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)

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

是的,在模板中,您将使用{% for item in collection %} -> {% 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 %}

应该是:

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

相关问题 更多 >