source: mailjam/postman/storage.py@ 10:d5329a2a05b7

Last change on this file since 10:d5329a2a05b7 was 5:573fdae8b1f6, checked in by Francisco de Borja Lopez Rio <borja@…>, 12 years ago

Added tests for postman.daemon.Postman

Added a method to postman.daemon.Postman to "clear" all the storage associated
to a given postman instance (removing all the files from disk)

Fixed some bugs, mostly caused by typos through the sources, detected while
writing more tests

Removed the storage and archive attributes from postman.models.MailingList,
now they are methods "marked" as properties using the @property decorator.
This keeps the storage objects from being serialized into json objects by
the storage backend (de-serializing them caused some trouble and it is not
necessary at all)

Added create() and delete() methods to postman.storage.JsonStorage. the first
one ensures the path to the storage file exists (creating all subdirs if
necessary) and the second one deletes the storage file from disk

File size: 2.7 KB
Line 
1# -*- coding: utf-8 -*-
2
3import os, errno, json
4
5
6class 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
Note: See TracBrowser for help on using the repository browser.