Transferring JSON data from server to client using Flask

I'm completely new to Flask, and I'm trying to figure out how to display data in a graph of a network using d3js syntax layouts. Here is the corresponding Python code:

@app.route("/")
def index():
    """
    When you request the root path, you'll get the index.html template.

    """
    return flask.render_template("index.html")


@app.route("/thread")
def get_graph_data(thread_id: int=3532967):
    """
    returns json of a network graph for the specified thread
    :param thread_id:
    :return:
    """
    pqdict, userdict = graphs.get_post_quote_dict(thread_id)
    G = graphs.create_graph(pqdict)
    s = graphs.graph_to_node_link(G, remove_singlets=True) # returns dict
    return flask.jsonify(s)

And here is the index.html file:

<!DOCTYPE html>
<html>
<head>
    <title>Index thing</title>
    <script type="text/javascript" src="http://d3js.org/d3.v2.js"></script>
    <link type="text/css" rel="stylesheet" href="templates/graph.css"/>
</head>
<body>
<div id="chart"></div>
<script>
    var w = 1500,
        h = 1500,
        fill = d3.scale.category20();

    var vis = d3.select("#chart")
        .append("svg:svg")
        .attr("width", w)
        .attr("height", h);

    d3.json("/thread", function (json) {
        var force = d3.layout.force()
            .charge(-120)
            .linkDistance(30)
            .nodes(json.nodes)
            .links(json.links)
            .size([w, h])
            .start();

        var link = vis.selectAll("line.link")
            .data(json.links)
            .enter().append("svg:line")
            .attr("class", "link")
            .style("stroke-width", function (d) {
                return Math.sqrt(d.value);
            })
            .attr("x1", function (d) {
                return d.source.x;
            })
            .attr("y1", function (d) {
                return d.source.y;
            })
            .attr("x2", function (d) {
                return d.target.x;
            })
            .attr("y2", function (d) {
                return d.target.y;
            });

        var node = vis.selectAll("circle.node")
            .data(json.nodes)
            .enter().append("svg:circle")
            .attr("class", "node")
            .attr("cx", function (d) {
                return d.x;
            })
            .attr("cy", function (d) {
                return d.y;
            })
            .attr("r", 5)
            .style("fill", function (d) {
                return fill(d.group);
            })
            .call(force.drag);

        vis.style("opacity", 1e-6)
            .transition()
            .duration(1000)
            .style("opacity", 1);

        force.on("tick", function () {
            link.attr("x1", function (d) {
                return d.source.x;
            })
                .attr("y1", function (d) {
                    return d.source.y;
                })
                .attr("x2", function (d) {
                    return d.target.x;
                })
                .attr("y2", function (d) {
                    return d.target.y;
                });

            node.attr("cx", function (d) {
                return d.x;
            })
                .attr("cy", function (d) {
                    return d.y;
                });
        });
    });
</script>
</body>
</html>

Thus, the d3.json () function requires the location of a static JSON file, which in this case I am trying to generate dynamically based on the request URL.

I tried about a dozen approaches that I found here. As suggested below, I tried:

@app.route("/")
def index():
    """
    When you request the root path, you'll get the index.html template.

    """
    return flask.render_template("index.html")


@app.route("/thread")
def get_graph_data():

    """
    returns json of a network graph for the specified thread
    :param thread_id:
    :return:
    """
    thread_id = request.args.get("thread_id", 3532967, type=int)
    pqdict, userdict = graphs.get_post_quote_dict(thread_id)
    G = graphs.create_graph(pqdict)
    s = graphs.graph_to_node_link(G, remove_singlets=True)
    return jsonify(s)

With the template, index.html did not change and switched to " http: // localhost / thread? Thread_id = 12345 ", but this failed because it printed the JSON ID for ID 12345 on the page instead of javascript rendering.

, - Python URL ( ".../showgraph? threadid = whatever..." ), json Python html/js. ?

+4
2

!

-, : ", d3.json() , JSON .

d3.json() d3-request , , XHR (, URL-, JSON, data.json, JSON).

Flask, GET, URL-:

@app.route("/thread")
def get_graph_data():
    thread_id = request.args.get("thread_id", 3532967, type=int)
    pqdict, userdict = graphs.get_post_quote_dict(thread_id)
    G = graphs.create_graph(pqdict)
    s = graphs.graph_to_node_link(G, remove_singlets=True) # returns dict
    return flask.jsonify(s)

, , :

@app.route("/thread/<int:thread_id>")
def get_graph_data(thread_id):
    ...

XHR- , GET:

var url = "/thread?thread_id=" + id.toString();
d3.json(url, function (json) {
    var force = d3.layout.force()
        .charge(-120)
        .linkDistance(30)
        .nodes(json.nodes)
        .links(json.links)
        .size([w, h])
        .start();

   // a bunch more js that i copied and pasted from a tutorial
});

.

, FYI, - Jinja2 "" Javascript Object, 2 : {{ data|tojson|safe }}

+5

:

Python:

@app.route("/thread")
def get_graph_data():

    """
    returns json of a network graph for the specified thread
    :param thread_id:
    :return:
    """
    thread_id = request.args.get("thread_id", 3532967, type=int)
    pqdict, userdict = graphs.get_post_quote_dict(thread_id)
    G = graphs.create_graph(pqdict)
    s = graphs.graph_to_node_link(G, remove_singlets=True)
    return json.dumps(s)


@app.route("/showgraph")
def showgraph():
    thread_id = request.args.get("thread_id", 3532967, type=int)
    return render_template("index.html", threadid=thread_id)

HTML/Jinja2:

<!DOCTYPE html>
<html>
<head>
    <title>Index thing</title>
    <script type="text/javascript" src="http://d3js.org/d3.v2.js"></script>
    <link type="text/css" rel="stylesheet" href="templates/graph.css"/>
</head>
<body>
<div id="chart"></div>
<script>
    var w = 1500,
        h = 1500,
        fill = d3.scale.category20();

    var vis = d3.select("#chart")
        .append("svg:svg")
        .attr("width", w)
        .attr("height", h);

    d3.json("/thread?thread_id={{ threadid }}", function (json) {
        var force = d3.layout.force()
            .charge(-120)
            .linkDistance(30)
            .nodes(json.nodes)
            .links(json.links)
            .size([w, h])
            .start();

        // irrelevant stuff
    });
</script>
</body>
</html>

JSON . - thread_id arg , . PJ, 99% !

+3

Source: https://habr.com/ru/post/1665178/


All Articles