无法从flask应用程序中的mysql.connector获取dict

2024-09-24 06:23:18 发布

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

我正在将flask应用程序从SQLite移植到MySQL。我的app.py中有以下内容:

def query_db(query, args=(), one=False):
    con = get_db()
    cur = con.cursor()
    cur.execute(query, args)

    result = cur.fetchall()

    cur.close()

    return (result[0] if result else None) if one else result

@app.route("/")
def index():

    rows = query_db("SELECT * FROM computers")

    return render_template("index.html", rows = rows)

在控制台中,我得到:

('FE:CB:40:50:B9:04', '192.168.11.163', 'Jules - Desktop (iMac)', None, 0, Decimal('0'), Decimal('0'), Decimal('0'), 0, 0, 0, 0, 0, 0, 0, 0, None, None, None, 1, 0, 0, None, None, 0, 0, '', 1, 1571097594)

在我的模板中,我有:

{% for row in rows %}
    <tr>
        <td>{{row['reboots']}}</td>
    </tr>
{% endfor %}

因此,当我尝试渲染我的模板时,我得到:

`jinja2.exceptions.UndefinedError: 'tuple object' has no attribute 'reboots'`

…其中reboots是数据库中的一个字段。在迁移到MySQL之前,我没有更改模式,因此我希望模板能够按原样工作。我需要把结果转换成口述还是什么


Tags: none模板appdbdefmysqlargsresult