1 | # -*- coding: utf-8 -*-
|
---|
2 |
|
---|
3 | import os, json
|
---|
4 |
|
---|
5 | class JsonStorage():
|
---|
6 |
|
---|
7 | """
|
---|
8 | Json-based storage.
|
---|
9 | """
|
---|
10 |
|
---|
11 | def __init__(self, path='storage.json'):
|
---|
12 | if os.path.isdir(path):
|
---|
13 | raise IOError(path, ' is a directory, exiting')
|
---|
14 | self.path = path
|
---|
15 |
|
---|
16 | def exists(self):
|
---|
17 | return os.path.exists(self.path)
|
---|
18 |
|
---|
19 | def jsonize(self, obj):
|
---|
20 | """
|
---|
21 | Convert objects to a dictionary of their representation
|
---|
22 | Based on the exmplaes from Doyg Hellmann:
|
---|
23 | http://www.doughellmann.com/PyMOTW/json/#working-with-your-own-types
|
---|
24 | """
|
---|
25 | jobj = { '__class__':obj.__class__.__name__,
|
---|
26 | '__module__':obj.__module__,
|
---|
27 | }
|
---|
28 | jobj.update(obj.__dict__)
|
---|
29 | return jobj
|
---|
30 |
|
---|
31 | def dejsonize(self, jobj):
|
---|
32 | """
|
---|
33 | Convert some data that has been "jsonized" to the original
|
---|
34 | python object. Again, based on the examples from Doug Hellmann
|
---|
35 | """
|
---|
36 | if '__class__' in jobj:
|
---|
37 | class_name = jobj.pop('__class__')
|
---|
38 | module_name = jobj.pop('__module__')
|
---|
39 | module = __import__(module_name)
|
---|
40 | class_ = getattr(module, class_name)
|
---|
41 | args = dict((key.encode('ascii'), value) \
|
---|
42 | for key, value in jobj.items())
|
---|
43 | return class_(**args)
|
---|
44 | return jobj
|
---|
45 |
|
---|
46 | def write(self, data):
|
---|
47 | with open(self.path, 'w') as storage:
|
---|
48 | json.dump(data, storage, sort_keys=True, indent=4,
|
---|
49 | default=self.jsonize)
|
---|
50 | return True
|
---|
51 | return False
|
---|
52 |
|
---|
53 | def read(self):
|
---|
54 | with open(self.path, 'r') as storage:
|
---|
55 | try:
|
---|
56 | data = json.load(storage,object_hook=self.dejsonize)
|
---|
57 | except ValueError:
|
---|
58 | # if no json data could be imported, the file could be
|
---|
59 | # damaged or perhaps it does not containg json-encoded
|
---|
60 | # data, simply return an empty string
|
---|
61 | #
|
---|
62 | # FIXME: we should notify the user about the problem
|
---|
63 | return ''
|
---|
64 | return data
|
---|
65 |
|
---|