1
+ import json
1
2
import logging
2
3
import os
3
4
from datetime import datetime
@@ -92,10 +93,13 @@ def get(self, path, trie=False):
92
93
# -- if trie is True, will return the data and the matching prefix
93
94
try_routes = self ._split_routes (path ) if trie else [path ]
94
95
for path in try_routes :
95
- doc = self .table .find_one (path = path )
96
+ doc = self .table .find_one (path = path , order_by = "id" )
96
97
if doc :
97
- data = self ._from_json (doc ["data" ] if not trie else doc )
98
- if trie :
98
+ if not trie :
99
+ data = self ._from_json (doc ["data" ])
100
+ else :
101
+ data = doc
102
+ data ["data" ] = self ._from_json (doc ["data" ])
99
103
data ["prefix" ] = path
100
104
break
101
105
else :
@@ -104,13 +108,15 @@ def get(self, path, trie=False):
104
108
105
109
def add (self , path , data ):
106
110
# add the data for the given exact path
107
- self .table .insert (self . _clean_json ( {"path" : path , "data" : data }) )
111
+ self .table .insert ({"path" : path , "data" : self . _to_json ( data )} )
108
112
109
113
def update (self , path , data ):
110
114
# update the data for the given exact path
111
- doc = self .table .find_one (path = path )
115
+ doc = self .table .find_one (path = path , order_by = "id" )
116
+ doc ["data" ] = self ._from_json (doc ["data" ])
112
117
doc ["data" ].update (data )
113
- self .table .update (self ._clean_json (doc ), "id" )
118
+ doc ["data" ] = self ._to_json (doc ["data" ])
119
+ self .table .update (doc , "id" )
114
120
115
121
def remove (self , path ):
116
122
# remove all matching routes for the given path
@@ -119,23 +125,24 @@ def remove(self, path):
119
125
120
126
def all (self ):
121
127
# return all data for all paths
122
- return self . _from_json ( {item ["path" ]: item ["data" ] for item in self .table .find ()})
128
+ return {item ["path" ]: self . _from_json ( item ["data" ]) for item in self .table .find (order_by = "id" )}
123
129
124
- def _clean_json (self , data ):
130
+ def _to_json (self , data ):
125
131
# simple converter for serializable data
126
132
for k , v in dict (data ).items ():
127
133
if isinstance (v , datetime ):
128
134
data [k ] = f"_dt_:{ v .isoformat ()} "
129
- if isinstance (v , dict ):
130
- data [k ] = self ._clean_json (v )
131
- return data
135
+ elif isinstance (v , dict ):
136
+ data [k ] = self ._to_json (v )
137
+ return json . dumps ( data )
132
138
133
139
def _from_json (self , data ):
134
140
# simple converter from serialized data
141
+ data = json .loads (data ) if isinstance (data , (str , bytes )) else data
135
142
for k , v in dict (data ).items ():
136
143
if isinstance (v , str ) and v .startswith ("_dt_:" ):
137
144
data [k ] = datetime .fromisoformat (v .split (":" , 1 )[- 1 ])
138
- if isinstance (v , dict ):
145
+ elif isinstance (v , dict ):
139
146
data [k ] = self ._from_json (v )
140
147
return data
141
148
0 commit comments