2017-07-25 71 views
0

我試圖從Flask API中獲取像這樣的JSON輸出,該API從MySQL數據庫獲取數據。使用python將MySQL輸出爲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和對不起。

回答

0

我找到了問題的答案。我將d.append(f)更改爲d['details'] = f