从Flask视图创建一个JSON文件,以便与D3一起使用 [英] Create a JSON file from a Flask view to be used with D3

查看:863
本文介绍了从Flask视图创建一个JSON文件,以便与D3一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用模板中某个D3代码中某个视图创建的JSON文件。我可以加载文件与D3与

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

如何创建并提供此文件从Flask视图?当我从IPython笔记本运行相同的脚本,我输出文件与

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

在这里你不需要(或者不想)写任何东西到文件中,你可以创建JSON和从烧瓶中返回它的方法:

  from flask import烧瓶,响应

@ 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){
// ...
//使用这些数据的操作
// ...
}


I need to use a JSON file created by one of the views in some D3 code in a template. I can load the file with D3 with

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

How can I create and serve this file from a Flask view? When I run the same script from IPython notebook I export the file with

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

but that instruction does not work from the view.

解决方案

You don't need (or want) to write anything to a file here. You can create the JSON and return it from a flask method:

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)

The d3 then becomes:

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

这篇关于从Flask视图创建一个JSON文件,以便与D3一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆