我对Flask和Python非常陌生,我必须将MySql查询转换为json格式。在转换时,我遇到了数值错误,无法理解,请帮助我,提前谢谢。
ValueError: dictionary update sequence element #0 has length 8; 2 is required on executing jsonify(r)
@app.route('/post')
def display():
cursor.execute("select * from tablename")
result=cursor.fetchall()
r = [dict((cursor.description[i][0], value) for i, value in enumerate(row)) for row in result]
return jsonify(r)发布于 2017-07-25 23:37:36
有一种更好的方法可以从MySQL查询中创建字典,它可以帮助您绕过所收到的错误。
在定义游标时,应该让它以字典列表的形式返回查询结果,如下所示:
cursor = connection.cursor(dictionary=True)
这样,从查询返回的表中的每一行都将作为列表中的字典存在。它看起来像这样:
[
{'firstcol': 'value1row1', 'secondcol': 'value2row1'... 'tenthcol': 'value10row1'},
{'firstcol': 'value1row2', 'secondcol': 'value2row2'... 'tenthcol': 'value10row2'},
...
{'firstcol': 'value1row50', 'secondcol': 'value2row50'... 'tenthcol': 'value10row50'}
]然后,对结果进行json化就变得非常简单:
return jsonify(result)
在那里,您将拥有一个JSON对象,其中包含可以通过key引用的元素。如果你想显示来自'firstcol‘的所有值,你只需要在你的JavaScript文件中使用response['firstcol']。
此外,为了确保你清楚Flask路由,标题你的路由'/post‘并不定义你的路由的'POST’方法。您需要:
@app.route('/post' methods=['POST'])
如果您已经意识到这一点,我很抱歉-我几个月前才开始学习Flask,最初对一些约定感到非常困惑,所以我想您可能和我处于同一条船上。
发布于 2017-07-28 21:06:18
您正在使用旧版本的Flask。0.12将jsonify更改为允许任何类型,以前只允许字典和元组列表。
pip install -U flaskhttps://stackoverflow.com/questions/45303803
复制相似问题