【问题标题】:MySQL output as JSON using python使用 python 将 MySQL 输出为 JSON
【发布时间】:2017-07-25 05:26:18
【问题描述】:

我试图从一个从 MySQL 数据库中获取数据的 Flask API 获得这样的 JSON 输出。

[{
  'date': '2016-01-01',
  'total': 17164,
  'details': [{
    'name': 'Project 1',
    'date': '2016-01-01 12:30:45',
    'value': 9192
  }, {
    'name': 'Project 2',
    'date': '2016-01-01 13:37:00',
    'value': 6753
  },
  {
    'name': 'Project N',
    'date': '2016-01-01 17:52:41',
    'value': 1219
  }]
}]

API定义是这样的:

@app.route('/api/getSalesHeatData', methods=['GET'])
@cross_origin() # allow all origins all methods.
def get_Sales_Heat_Data():
db = getMysqlConnection()
print(db)
try:
    sqlstr1 = "SELECT InvoiceDateOnly, sum(Quantity) from testing group by InvoiceDateOnly"
    print(sqlstr1)
    sqlstr2 = "SELECT InvoiceDateOnly, Description, Quantity from testing"
    print(sqlstr2)
    cur1 = db.cursor()
    cur1.execute(sqlstr1)
    output_json1 = cur1.fetchall()
    cur2 = db.cursor()
    cur2.execute(sqlstr2)
    output_json2 = cur2.fetchall()
    user_list = []
    for row1 in output_json1:
        d = collections.OrderedDict()
        d['date']  = str(row1[0])
        d['total']   = row1[1]
        for row2 in output_json2:
           if row1[0] == row2[0]:
               f = collections.OrderedDict()
               f['desc']   = row2[1]
               f['date']   = str(row2[0])
               f['qty']   = row2[2]
               d.append(f)
        user_list.append(d)
except Exception as e:
    print("Error in SQL:\n", e)
finally:
    db.close()
return json.dumps(user_list)`

输出在终端中返回错误,但显示状态 200 没有数据。请就此给我建议。我是 python 新手,如果这是一个愚蠢的错误,请原谅我。

【问题讨论】:

    标签: mysql json python-3.x


    【解决方案1】:

    我找到了问题的答案。我将d.append(f) 更改为d['details'] = f

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 2019-02-04
      • 2019-07-24
      • 2014-08-16
      相关资源
      最近更新 更多