首页 > 解决方案 > 使用 spycopg2 Python Flask 填充 HTML Select

问题描述

我是使用烧瓶的新手,我想提取该数据并使用 FLASK 以 html 形式将其显示为选择选项。这是我的选择

<span class="input-group-addon">Unity</span>
    <select name="unity" class="selectpicker form-control">

    </select>

我想用这些数据填充它

@app.route("/stadistics/unity")
def unity():
    db = get_db()
    cursor = db.cursor()
    cursor.execute("select unity from mse.unity")
    unity = cursor.fetchall()
    print (unity)

我怎么能这样做?

标签: pythonhtmlpostgresqlflaskpsycopg2

解决方案


Python代码:

@app.route("/stadistics/unity")
def unity():
    db = get_db()
    cursor = db.cursor()
    cursor.execute("select unity from mse.unity")
    unity = cursor.fetchall()
    return render_template('my_html_file.html', unity=unity)

HTML,带有 Jinja2 for 循环:

<select name="unity" class="selectpicker form-control">
    {% for u in unity %}
    <option value="{{ u }}">{{ u }}</option>
    {% endfor %}
</select>

Flask 默认包含 Jinja2 模板引擎,您可以将您选择的变量传递给您的 HTML 模板,当您调用时render_template(),请查看文档以获取更多详细信息:https ://flask.palletsprojects.com/en/1.1.x /quickstart/#rendering-templates


推荐阅读