-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph_store.py
106 lines (85 loc) · 2.93 KB
/
graph_store.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///graph.db'
db = SQLAlchemy(app)
class Node(db.Model):
__tablename__ = 'node'
id = db.Column(db.Integer, primary_key=True)
x = db.Column(db.Integer)
y = db.Column(db.Integer)
name = db.Column(db.String(20))
graph_id = db.Column(db.Integer, db.ForeignKey('graph.id'))
class Edge(db.Model):
__tablename__ = 'edge'
id = db.Column(db.Integer, primary_key=True)
first_node = db.Column(db.Integer)
second_node = db.Column(db.Integer)
weight = db.Column(db.Integer)
graph_id = db.Column(db.Integer, db.ForeignKey('graph.id'))
class Graph(db.Model):
__tablename__ = 'graph'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
description = db.Column(db.Text)
nodes = db.relationship('Node', backref='graph', lazy=True)
edges = db.relationship('Edge', backref='graph', lazy=True)
def add_graph(nodes, edges, graph_name, graph_description):
session = db.session
new_graph = Graph(name=graph_name, description=graph_description)
session.add(new_graph)
session.commit()
graph_id = new_graph.id
try:
for node in nodes:
new_node = Node(x=node['x'], y=node['y'], name=node['name'], graph_id=graph_id)
session.add(new_node)
session.commit()
for edge in edges:
new_edge = Edge(first_node=edge['first_node'], second_node=edge['second_node'], weight=edge['weight'], graph_id=graph_id)
session.add(new_edge)
session.commit()
return jsonify('success')
except Exception as e:
session.rollback()
return jsonify({'error': e}), 500
finally:
session.close()
def load_graphs():
try:
graphs = Graph.query.all()
graph_list = []
for graph in graphs:
graph_list.append({
'id': graph.id,
'name': graph.name
})
return jsonify(graph_list)
except Exception as e:
return jsonify({'error': str(e)}), 500
def load_graph(graph_id):
try:
graph = Graph.query.get(graph_id)
if graph is None:
return jsonify({'error': 'Graph not found'}), 404
graph_data = {
'id': graph.id,
'name': graph.name,
'nodes': [],
'edges': []
}
for node in graph.nodes:
graph_data['nodes'].append({
'name': node.name,
'x': node.x,
'y': node.y
})
for edge in graph.edges:
graph_data['edges'].append({
'first_node': edge.first_node,
'second_node': edge.second_node,
'weight': edge.weight
})
return jsonify(graph_data)
except Exception as e:
return jsonify({'error': str(e)}), 500