2016-03-01 45 views
2

我需要使用模板中某些D3代碼中某個視圖創建的JSON文件。我可以用D3加載文件從Flask視圖創建JSON文件以與D3一起使用

d3.json("nameOfTheFile.json", function (error, data) { 
    // ... 
} 

如何從Flask視圖創建並提供此文件?當我從IPython筆記本運行相同的腳本時,我使用

dataFrame.to_json(nameOfTheFile.json, orient='records', date_format='iso') 

導出文件,但該指令在視圖中不起作用。

+0

謝謝。我沒有記得那樣寫代碼。 –

回答

3

你不需要(或不想)在這裏寫入任何文件。您可以創建JSON並從燒瓶方法返回它:

from flask import Flask, Response 

@app.route('/getMyJson') 
def getMyJson(): 
    json = dataFrame.to_json(orient='records', date_format='iso') 
    response = Response(response=json, status=200, mimetype="application/json") 
    return(response) 

d3就變成了:

d3.json("/getMyJson", function (error, data) { 
    // ... 
    // Operations with those data 
    // ... 
} 
+0

這就是我要找的。非常感謝。 –