source: mailjam/postman/storage.py@ 14:0a6affee82cd

Last change on this file since 14:0a6affee82cd was 11:078c7b030cee, checked in by Borja Lopez <borja@…>, 13 years ago

Removed legacy configs from the config module

Added some headers to the sources (setting author, email, website
and references to the LICENSE)

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