aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/persisted/dirdbm.py
blob: 26bbc1b28720b7a2da2803b30b2402952109399b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# -*- test-case-name: twisted.test.test_dirdbm -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.



"""
DBM-style interface to a directory.

Each key is stored as a single file.  This is not expected to be very fast or
efficient, but it's good for easy debugging.

DirDBMs are *not* thread-safe, they should only be accessed by one thread at
a time.

No files should be placed in the working directory of a DirDBM save those
created by the DirDBM itself!

Maintainer: Itamar Shtull-Trauring
"""


import os
import types
import base64
import glob

try:
    import cPickle as pickle
except ImportError:
    import pickle

try:
    _open
except NameError:
    _open = open


class DirDBM:
    """A directory with a DBM interface.
    
    This class presents a hash-like interface to a directory of small,
    flat files. It can only use strings as keys or values.
    """
    
    def __init__(self, name):
        """
        @type name: str
        @param name: Base path to use for the directory storage.
        """
        self.dname = os.path.abspath(name)
        if not os.path.isdir(self.dname):
            os.mkdir(self.dname)
        else:
            # Run recovery, in case we crashed. we delete all files ending
            # with ".new". Then we find all files who end with ".rpl". If a
            # corresponding file exists without ".rpl", we assume the write
            # failed and delete the ".rpl" file. If only a ".rpl" exist we
            # assume the program crashed right after deleting the old entry
            # but before renaming the replacement entry.
            #
            # NOTE: '.' is NOT in the base64 alphabet!
            for f in glob.glob(os.path.join(self.dname, "*.new")):
                os.remove(f)
            replacements = glob.glob(os.path.join(self.dname, "*.rpl"))
            for f in replacements:
                old = f[:-4]
                if os.path.exists(old):
                    os.remove(f)
                else:
                    os.rename(f, old)
    
    def _encode(self, k):
        """Encode a key so it can be used as a filename.
        """
        # NOTE: '_' is NOT in the base64 alphabet!
        return base64.encodestring(k).replace('\n', '_').replace("/", "-")
    
    def _decode(self, k):
        """Decode a filename to get the key.
        """
        return base64.decodestring(k.replace('_', '\n').replace("-", "/"))
    
    def _readFile(self, path):
        """Read in the contents of a file.
        
        Override in subclasses to e.g. provide transparently encrypted dirdbm.
        """
        f = _open(path, "rb")
        s = f.read()
        f.close()
        return s
    
    def _writeFile(self, path, data):
        """Write data to a file.
        
        Override in subclasses to e.g. provide transparently encrypted dirdbm.
        """
        f = _open(path, "wb")
        f.write(data)
        f.flush()
        f.close()
    
    def __len__(self):
        """
        @return: The number of key/value pairs in this Shelf
        """
        return len(os.listdir(self.dname))

    def __setitem__(self, k, v):
        """
        C{dirdbm[k] = v}
        Create or modify a textfile in this directory

        @type k: str
        @param k: key to set
        
        @type v: str
        @param v: value to associate with C{k}
        """
        assert type(k) == types.StringType, "DirDBM key must be a string"
        assert type(v) == types.StringType, "DirDBM value must be a string"
        k = self._encode(k)
        
        # we create a new file with extension .new, write the data to it, and
        # if the write succeeds delete the old file and rename the new one.
        old = os.path.join(self.dname, k)
        if os.path.exists(old):
            new = old + ".rpl" # replacement entry
        else:
            new = old + ".new" # new entry
        try:
            self._writeFile(new, v)
        except:
            os.remove(new)
            raise
        else:
            if os.path.exists(old): os.remove(old)
            os.rename(new, old)

    def __getitem__(self, k):
        """
        C{dirdbm[k]}
        Get the contents of a file in this directory as a string.
        
        @type k: str
        @param k: key to lookup
        
        @return: The value associated with C{k}
        @raise KeyError: Raised when there is no such key
        """
        assert type(k) == types.StringType, "DirDBM key must be a string"
        path = os.path.join(self.dname, self._encode(k))
        try:
            return self._readFile(path)
        except:
            raise KeyError, k

    def __delitem__(self, k):
        """
        C{del dirdbm[foo]}
        Delete a file in this directory.
        
        @type k: str
        @param k: key to delete
        
        @raise KeyError: Raised when there is no such key
        """
        assert type(k) == types.StringType, "DirDBM key must be a string"
        k = self._encode(k)
        try:    os.remove(os.path.join(self.dname, k))
        except (OSError, IOError): raise KeyError(self._decode(k))

    def keys(self):
        """
        @return: a C{list} of filenames (keys).
        """
        return map(self._decode, os.listdir(self.dname))

    def values(self):
        """
        @return: a C{list} of file-contents (values).
        """
        vals = []
        keys = self.keys()
        for key in keys:
            vals.append(self[key])
        return vals

    def items(self):
        """
        @return: a C{list} of 2-tuples containing key/value pairs.
        """
        items = []
        keys = self.keys()
        for key in keys:
            items.append((key, self[key]))
        return items

    def has_key(self, key):
        """
        @type key: str
        @param key: The key to test
        
        @return: A true value if this dirdbm has the specified key, a faluse
        value otherwise.
        """
        assert type(key) == types.StringType, "DirDBM key must be a string"
        key = self._encode(key)
        return os.path.isfile(os.path.join(self.dname, key))

    def setdefault(self, key, value):
        """
        @type key: str
        @param key: The key to lookup
        
        @param value: The value to associate with key if key is not already
        associated with a value.
        """
        if not self.has_key(key):
            self[key] = value
            return value
        return self[key]

    def get(self, key, default = None):
        """
        @type key: str
        @param key: The key to lookup
        
        @param default: The value to return if the given key does not exist
        
        @return: The value associated with C{key} or C{default} if not
        C{self.has_key(key)}
        """
        if self.has_key(key):
            return self[key]
        else:
            return default

    def __contains__(self, key):
        """
        C{key in dirdbm}

        @type key: str
        @param key: The key to test
                
        @return: A true value if C{self.has_key(key)}, a false value otherwise.
        """
        assert type(key) == types.StringType, "DirDBM key must be a string"
        key = self._encode(key)
        return os.path.isfile(os.path.join(self.dname, key))

    def update(self, dict):
        """
        Add all the key/value pairs in C{dict} to this dirdbm.  Any conflicting
        keys will be overwritten with the values from C{dict}.

        @type dict: mapping
        @param dict: A mapping of key/value pairs to add to this dirdbm.
        """
        for key, val in dict.items():
            self[key]=val
            
    def copyTo(self, path):
        """
        Copy the contents of this dirdbm to the dirdbm at C{path}.
        
        @type path: C{str}
        @param path: The path of the dirdbm to copy to.  If a dirdbm
        exists at the destination path, it is cleared first.
        
        @rtype: C{DirDBM}
        @return: The dirdbm this dirdbm was copied to.
        """
        path = os.path.abspath(path)
        assert path != self.dname
        
        d = self.__class__(path)
        d.clear()
        for k in self.keys():
            d[k] = self[k]
        return d

    def clear(self):
        """
        Delete all key/value pairs in this dirdbm.
        """
        for k in self.keys():
            del self[k]

    def close(self):
        """
        Close this dbm: no-op, for dbm-style interface compliance.
        """

    def getModificationTime(self, key):
        """
        Returns modification time of an entry.
        
        @return: Last modification date (seconds since epoch) of entry C{key}
        @raise KeyError: Raised when there is no such key
        """
        assert type(key) == types.StringType, "DirDBM key must be a string"
        path = os.path.join(self.dname, self._encode(key))
        if os.path.isfile(path):
            return os.path.getmtime(path)
        else:
            raise KeyError, key


class Shelf(DirDBM):
    """A directory with a DBM shelf interface.
    
    This class presents a hash-like interface to a directory of small,
    flat files. Keys must be strings, but values can be any given object.
    """
    
    def __setitem__(self, k, v):
        """
        C{shelf[foo] = bar}
        Create or modify a textfile in this directory.

        @type k: str
        @param k: The key to set

        @param v: The value to associate with C{key}
        """
        v = pickle.dumps(v)
        DirDBM.__setitem__(self, k, v)

    def __getitem__(self, k):
        """
        C{dirdbm[foo]}
        Get and unpickle the contents of a file in this directory.
        
        @type k: str
        @param k: The key to lookup
        
        @return: The value associated with the given key
        @raise KeyError: Raised if the given key does not exist
        """
        return pickle.loads(DirDBM.__getitem__(self, k))


def open(file, flag = None, mode = None):
    """
    This is for 'anydbm' compatibility.
    
    @param file: The parameter to pass to the DirDBM constructor.

    @param flag: ignored
    @param mode: ignored
    """
    return DirDBM(file)


__all__ = ["open", "DirDBM", "Shelf"]