这几天一直在期待能搞到个便捷的方法,把数据库查询游标按照查询字段直接转变为字典甚至是json来,终于在网上找到了,改编了一下:
def cur2json(cursor):
if cursor.description is None: return []
cols = [c[0].lower() for c in cursor.description]
'''
Column name is always lower case.
:param cursor:
:return:
'''
data = [dict(zip(cols, row)) for row in cursor.fetchall()]
# 实际在这里先把游标转变为dict然后再jsonify
return jsonify(data)
正常使用的时候是这样:
@app.route('/p/l/incity/')
# 按城市获得项目列表
def get_project_list_by_city(cid):
sql1 = 'SELECT id, name, id_town, location, path_pic,'
sql2 = 'price_low, price_high, credit, popularity, '
sql3 = 'bounty, amount_rewards FROM projects'
sql4 = 'WHERE id_city = %d' % cid
cur = g.db.execute('%s %s %s %s;' % (sql1, sql2, sql3, sql4))
return cur2json(cur)
实际使用中(上述并未改动)我把cur也放进函数里写了,直接从sql语句变成json,一步到位(有特殊需求的位置单独再拆)
via Python / Flask / SQLite3