Skip to content

Instantly share code, notes, and snippets.

@DavidRayner
Last active May 21, 2018 12:15
Show Gist options
  • Save DavidRayner/74976dd904582f24b4bd9e1e4ef6d96d to your computer and use it in GitHub Desktop.
Save DavidRayner/74976dd904582f24b4bd9e1e4ef6d96d to your computer and use it in GitHub Desktop.
SigmaJS Export to server (flask)

SigmaJS Export to Server

This is how I save the nodes and edges of a sigma graph into a JSON file. The JSON file can be later re-imported with the sigma.parsers.json plugin.

Frontend

HTML

<button id="export-btn">Save Graph On Server</button><br/>

JS

$('#export-btn').click(function(event) {
  var filename = prompt("What do you want to name the saved graph?");
  data = {
    'graph': {
      'nodes': s.graph.nodes(),
      'edges': s.graph.edges()
    },
    'filename': filename
  }

  $.ajax({
    type: 'post',
    url: '/save-graph',
    data: JSON.stringify(data),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
  });
});

Backend (Flask)

You probably want to use secure_filename

@app.route('/save-graph', methods=['POST'])
def save_graph():
    data = json.loads(request.data)
    graph_data = data['graph']
    filename = data['filename']
    if not filename.endswith('.json'):
        filename += '.json'

    with open('viz/data/' + filename, 'w', encoding='utf-8') as file:
        file.write(json.dumps(graph_data, indent=2))
    return 'Success'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment