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