0
|
1 from abc import abstractmethod
|
|
2
|
|
3 class GraphModel(object):
|
|
4
|
|
5 @abstractmethod
|
|
6 def node(self, name, **values):
|
|
7 """get or set a node"""
|
|
8
|
|
9 @abstractmethod
|
|
10 def nodes(self):
|
|
11 """returns a list of all nodes"""
|
|
12
|
|
13 @abstractmethod
|
|
14 def edges(self):
|
|
15 """returns a list of all edges"""
|
|
16
|
|
17 @abstractmethod
|
|
18 def edge(self, node1, node2, **values):
|
|
19 """returns edge from node1 to node2"""
|
|
20
|
|
21 def __getitem__(self, key):
|
|
22 """
|
|
23 if key is a basestring, return the node of that name;
|
|
24 if key is a 2-tuple/list, return the edge of that name
|
|
25 """
|
|
26
|
|
27
|
|
28 class MemoryCache(GraphModel):
|
|
29
|
|
30 def __init__(self):
|
|
31 self._edges = {}
|
|
32 self._nodes = {}
|
|
33
|
|
34 def node(self, name, **values):
|
|
35 if values:
|
|
36 # setter
|
|
37 self._nodes[name] = values
|
|
38 else:
|
|
39 # getter
|
|
40 return self._nodes.get(name, None)
|
|
41
|
|
42 def nodes(self):
|
|
43 return self._nodes.keys()
|
|
44
|
|
45 def edge(self, node1, node2, **values):
|
|
46 if values:
|
|
47 # setter
|
|
48 self._edges[(node1, node2)] = values
|
|
49 else:
|
|
50 # getter
|
|
51 return self._edges.get((node1, node2), None)
|
|
52
|
|
53 def edges(self):
|
|
54 return self._edges.keys()
|