簡體   English   中英

從SQLITE到Flask頁面中的HTML表的數據

[英]Data from SQLITE to an HTML table in a Flask page

我在SQLite3中有一個表,我需要處理表中幾乎所有列並將其輸出到網頁。 對於其他頁面,我使用了flask,但這始終是將3或4個單值變量傳遞到模板中的情況。

我猜這就像是將游標或更可能是將cursor.fetchall()調用中的行cursor.fetchall()到模板中,然后在模板中逐行循環一樣?

它應該是:

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

將數據作為某種集合傳遞,無論是像官方教程中的字典一樣,還是更簡單的東西(如元組或列表)。

是的,在模板中,您將使用{% 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 %}

您需要遵循以下步驟:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM