desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create a message, with text from the open file txt.'
def createmessage(self, n, txt):
path = self.getmessagefilename(n) backuppath = self.getmessagefilename((',%d' % n)) try: os.rename(path, backuppath) except os.error: pass ok = 0 BUFSIZE = (16 * 1024) try: f = open(path, 'w') while 1: buf = txt.read(BUFSIZE) if (not buf): break f.write(buf) f.close() ok = 1 finally: if (not ok): try: os.unlink(path) except os.error: pass
'Remove one or more messages from all sequences (including last) -- but not from \'cur\'!!!'
def removefromallsequences(self, list):
if (hasattr(self, 'last') and (self.last in list)): del self.last sequences = self.getsequences() changed = 0 for (name, seq) in sequences.items(): if (name == 'cur'): continue for n in list: if (n in seq): seq.remove(n) changed = 1 if (not seq): del sequences[name] if changed: self.putsequences(sequences)
'Return the last message number.'
def getlast(self):
if (not hasattr(self, 'last')): self.listmessages() return self.last
'Set the last message number.'
def setlast(self, last):
if (last is None): if hasattr(self, 'last'): del self.last else: self.last = last
'Constructor.'
def __init__(self, f, n, fp=None):
self.folder = f self.number = n if (fp is None): path = f.getmessagefilename(n) fp = open(path, 'r') mimetools.Message.__init__(self, fp)
'String representation.'
def __repr__(self):
return ('Message(%s, %s)' % (repr(self.folder), self.number))
'Return the message\'s header text as a string. If an argument is specified, it is used as a filter predicate to decide which headers to return (its argument is the header name converted to lower case).'
def getheadertext(self, pred=None):
if (pred is None): return ''.join(self.headers) headers = [] hit = 0 for line in self.headers: if (not line[0].isspace()): i = line.find(':') if (i > 0): hit = pred(line[:i].lower()) if hit: headers.append(line) return ''.join(headers)
'Return the message\'s body text as string. This undoes a Content-Transfer-Encoding, but does not interpret other MIME features (e.g. multipart messages). To suppress decoding, pass 0 as an argument.'
def getbodytext(self, decode=1):
self.fp.seek(self.startofbody) encoding = self.getencoding() if ((not decode) or (encoding in ('', '7bit', '8bit', 'binary'))): return self.fp.read() try: from cStringIO import StringIO except ImportError: from StringIO import StringIO output = StringIO() mimetools.decode(self.fp, output, encoding) return output.getvalue()
'Only for multipart messages: return the message\'s body as a list of SubMessage objects. Each submessage object behaves (almost) as a Message object.'
def getbodyparts(self):
if (self.getmaintype() != 'multipart'): raise Error, 'Content-Type is not multipart/*' bdry = self.getparam('boundary') if (not bdry): raise Error, 'multipart/* without boundary param' self.fp.seek(self.startofbody) mf = multifile.MultiFile(self.fp) mf.push(bdry) parts = [] while mf.next(): n = ('%s.%r' % (self.number, (1 + len(parts)))) part = SubMessage(self.folder, n, mf) parts.append(part) mf.pop() return parts
'Return body, either a string or a list of messages.'
def getbody(self):
if (self.getmaintype() == 'multipart'): return self.getbodyparts() else: return self.getbodytext()
'Constructor.'
def __init__(self, f, n, fp):
Message.__init__(self, f, n, fp) if (self.getmaintype() == 'multipart'): self.body = Message.getbodyparts(self) else: self.body = Message.getbodytext(self) self.bodyencoded = Message.getbodytext(self, decode=0)
'String representation.'
def __repr__(self):
(f, n, fp) = (self.folder, self.number, self.fp) return ('SubMessage(%s, %s, %s)' % (f, n, fp))
'Return an iterator that yields the weak references to the values. The references are not guaranteed to be \'live\' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the values around longer than needed.'
def itervaluerefs(self):
return self.data.itervalues()
'Return a list of weak references to the values. The references are not guaranteed to be \'live\' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the values around longer than needed.'
def valuerefs(self):
return self.data.values()
'Return an iterator that yields the weak references to the keys. The references are not guaranteed to be \'live\' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the keys around longer than needed.'
def iterkeyrefs(self):
return self.data.iterkeys()
'Return a list of weak references to the keys. The references are not guaranteed to be \'live\' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the keys around longer than needed.'
def keyrefs(self):
return self.data.keys()
'Initialize a Mailbox instance.'
def __init__(self, path, factory=None, create=True):
self._path = os.path.abspath(os.path.expanduser(path)) self._factory = factory
'Add message and return assigned key.'
def add(self, message):
raise NotImplementedError('Method must be implemented by subclass')
'Remove the keyed message; raise KeyError if it doesn\'t exist.'
def remove(self, key):
raise NotImplementedError('Method must be implemented by subclass')
'If the keyed message exists, remove it.'
def discard(self, key):
try: self.remove(key) except KeyError: pass
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
def __setitem__(self, key, message):
raise NotImplementedError('Method must be implemented by subclass')
'Return the keyed message, or default if it doesn\'t exist.'
def get(self, key, default=None):
try: return self.__getitem__(key) except KeyError: return default
'Return the keyed message; raise KeyError if it doesn\'t exist.'
def __getitem__(self, key):
if (not self._factory): return self.get_message(key) else: return self._factory(self.get_file(key))
'Return a Message representation or raise a KeyError.'
def get_message(self, key):
raise NotImplementedError('Method must be implemented by subclass')
'Return a string representation or raise a KeyError.'
def get_string(self, key):
raise NotImplementedError('Method must be implemented by subclass')
'Return a file-like representation or raise a KeyError.'
def get_file(self, key):
raise NotImplementedError('Method must be implemented by subclass')
'Return an iterator over keys.'
def iterkeys(self):
raise NotImplementedError('Method must be implemented by subclass')
'Return a list of keys.'
def keys(self):
return list(self.iterkeys())
'Return an iterator over all messages.'
def itervalues(self):
for key in self.iterkeys(): try: value = self[key] except KeyError: continue (yield value)
'Return a list of messages. Memory intensive.'
def values(self):
return list(self.itervalues())
'Return an iterator over (key, message) tuples.'
def iteritems(self):
for key in self.iterkeys(): try: value = self[key] except KeyError: continue (yield (key, value))
'Return a list of (key, message) tuples. Memory intensive.'
def items(self):
return list(self.iteritems())
'Return True if the keyed message exists, False otherwise.'
def has_key(self, key):
raise NotImplementedError('Method must be implemented by subclass')
'Return a count of messages in the mailbox.'
def __len__(self):
raise NotImplementedError('Method must be implemented by subclass')
'Delete all messages.'
def clear(self):
for key in self.iterkeys(): self.discard(key)
'Delete the keyed message and return it, or default.'
def pop(self, key, default=None):
try: result = self[key] except KeyError: return default self.discard(key) return result
'Delete an arbitrary (key, message) pair and return it.'
def popitem(self):
for key in self.iterkeys(): return (key, self.pop(key)) else: raise KeyError('No messages in mailbox')
'Change the messages that correspond to certain keys.'
def update(self, arg=None):
if hasattr(arg, 'iteritems'): source = arg.iteritems() elif hasattr(arg, 'items'): source = arg.items() else: source = arg bad_key = False for (key, message) in source: try: self[key] = message except KeyError: bad_key = True if bad_key: raise KeyError('No message with key(s)')
'Write any pending changes to the disk.'
def flush(self):
raise NotImplementedError('Method must be implemented by subclass')
'Lock the mailbox.'
def lock(self):
raise NotImplementedError('Method must be implemented by subclass')
'Unlock the mailbox if it is locked.'
def unlock(self):
raise NotImplementedError('Method must be implemented by subclass')
'Flush and close the mailbox.'
def close(self):
raise NotImplementedError('Method must be implemented by subclass')
'Dump message contents to target file.'
def _dump_message(self, message, target, mangle_from_=False):
if isinstance(message, email.message.Message): buffer = StringIO.StringIO() gen = email.generator.Generator(buffer, mangle_from_, 0) gen.flatten(message) buffer.seek(0) target.write(buffer.read().replace('\n', os.linesep)) elif isinstance(message, str): if mangle_from_: message = message.replace('\nFrom ', '\n>From ') message = message.replace('\n', os.linesep) target.write(message) elif hasattr(message, 'read'): while True: line = message.readline() if (line == ''): break if (mangle_from_ and line.startswith('From ')): line = ('>From ' + line[5:]) line = line.replace('\n', os.linesep) target.write(line) else: raise TypeError(('Invalid message type: %s' % type(message)))
'Initialize a Maildir instance.'
def __init__(self, dirname, factory=rfc822.Message, create=True):
Mailbox.__init__(self, dirname, factory, create) self._paths = {'tmp': os.path.join(self._path, 'tmp'), 'new': os.path.join(self._path, 'new'), 'cur': os.path.join(self._path, 'cur')} if (not os.path.exists(self._path)): if create: os.mkdir(self._path, 448) for path in self._paths.values(): os.mkdir(path, 448) else: raise NoSuchMailboxError(self._path) self._toc = {} self._toc_mtimes = {} for subdir in ('cur', 'new'): self._toc_mtimes[subdir] = os.path.getmtime(self._paths[subdir]) self._last_read = time.time() self._skewfactor = 0.1
'Add message and return assigned key.'
def add(self, message):
tmp_file = self._create_tmp() try: self._dump_message(message, tmp_file) except BaseException: tmp_file.close() os.remove(tmp_file.name) raise _sync_close(tmp_file) if isinstance(message, MaildirMessage): subdir = message.get_subdir() suffix = (self.colon + message.get_info()) if (suffix == self.colon): suffix = '' else: subdir = 'new' suffix = '' uniq = os.path.basename(tmp_file.name).split(self.colon)[0] dest = os.path.join(self._path, subdir, (uniq + suffix)) try: if hasattr(os, 'link'): os.link(tmp_file.name, dest) os.remove(tmp_file.name) else: os.rename(tmp_file.name, dest) except OSError as e: os.remove(tmp_file.name) if (e.errno == errno.EEXIST): raise ExternalClashError(('Name clash with existing message: %s' % dest)) else: raise if isinstance(message, MaildirMessage): os.utime(dest, (os.path.getatime(dest), message.get_date())) return uniq
'Remove the keyed message; raise KeyError if it doesn\'t exist.'
def remove(self, key):
os.remove(os.path.join(self._path, self._lookup(key)))
'If the keyed message exists, remove it.'
def discard(self, key):
try: self.remove(key) except KeyError: pass except OSError as e: if (e.errno != errno.ENOENT): raise
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
def __setitem__(self, key, message):
old_subpath = self._lookup(key) temp_key = self.add(message) temp_subpath = self._lookup(temp_key) if isinstance(message, MaildirMessage): dominant_subpath = temp_subpath else: dominant_subpath = old_subpath subdir = os.path.dirname(dominant_subpath) if (self.colon in dominant_subpath): suffix = (self.colon + dominant_subpath.split(self.colon)[(-1)]) else: suffix = '' self.discard(key) new_path = os.path.join(self._path, subdir, (key + suffix)) os.rename(os.path.join(self._path, temp_subpath), new_path) if isinstance(message, MaildirMessage): os.utime(new_path, (os.path.getatime(new_path), message.get_date()))
'Return a Message representation or raise a KeyError.'
def get_message(self, key):
subpath = self._lookup(key) f = open(os.path.join(self._path, subpath), 'r') try: if self._factory: msg = self._factory(f) else: msg = MaildirMessage(f) finally: f.close() (subdir, name) = os.path.split(subpath) msg.set_subdir(subdir) if (self.colon in name): msg.set_info(name.split(self.colon)[(-1)]) msg.set_date(os.path.getmtime(os.path.join(self._path, subpath))) return msg
'Return a string representation or raise a KeyError.'
def get_string(self, key):
f = open(os.path.join(self._path, self._lookup(key)), 'r') try: return f.read() finally: f.close()
'Return a file-like representation or raise a KeyError.'
def get_file(self, key):
f = open(os.path.join(self._path, self._lookup(key)), 'rb') return _ProxyFile(f)
'Return an iterator over keys.'
def iterkeys(self):
self._refresh() for key in self._toc: try: self._lookup(key) except KeyError: continue (yield key)
'Return True if the keyed message exists, False otherwise.'
def has_key(self, key):
self._refresh() return (key in self._toc)
'Return a count of messages in the mailbox.'
def __len__(self):
self._refresh() return len(self._toc)
'Write any pending changes to disk.'
def flush(self):
pass
'Lock the mailbox.'
def lock(self):
return
'Unlock the mailbox if it is locked.'
def unlock(self):
return
'Flush and close the mailbox.'
def close(self):
return
'Return a list of folder names.'
def list_folders(self):
result = [] for entry in os.listdir(self._path): if ((len(entry) > 1) and (entry[0] == '.') and os.path.isdir(os.path.join(self._path, entry))): result.append(entry[1:]) return result
'Return a Maildir instance for the named folder.'
def get_folder(self, folder):
return Maildir(os.path.join(self._path, ('.' + folder)), factory=self._factory, create=False)
'Create a folder and return a Maildir instance representing it.'
def add_folder(self, folder):
path = os.path.join(self._path, ('.' + folder)) result = Maildir(path, factory=self._factory) maildirfolder_path = os.path.join(path, 'maildirfolder') if (not os.path.exists(maildirfolder_path)): os.close(os.open(maildirfolder_path, (os.O_CREAT | os.O_WRONLY), 438)) return result
'Delete the named folder, which must be empty.'
def remove_folder(self, folder):
path = os.path.join(self._path, ('.' + folder)) for entry in (os.listdir(os.path.join(path, 'new')) + os.listdir(os.path.join(path, 'cur'))): if ((len(entry) < 1) or (entry[0] != '.')): raise NotEmptyError(('Folder contains message(s): %s' % folder)) for entry in os.listdir(path): if ((entry != 'new') and (entry != 'cur') and (entry != 'tmp') and os.path.isdir(os.path.join(path, entry))): raise NotEmptyError(("Folder contains subdirectory '%s': %s" % (folder, entry))) for (root, dirs, files) in os.walk(path, topdown=False): for entry in files: os.remove(os.path.join(root, entry)) for entry in dirs: os.rmdir(os.path.join(root, entry)) os.rmdir(path)
'Delete old files in "tmp".'
def clean(self):
now = time.time() for entry in os.listdir(os.path.join(self._path, 'tmp')): path = os.path.join(self._path, 'tmp', entry) if ((now - os.path.getatime(path)) > 129600): os.remove(path)
'Create a file in the tmp subdirectory and open and return it.'
def _create_tmp(self):
now = time.time() hostname = socket.gethostname() if ('/' in hostname): hostname = hostname.replace('/', '\\057') if (':' in hostname): hostname = hostname.replace(':', '\\072') uniq = ('%s.M%sP%sQ%s.%s' % (int(now), int(((now % 1) * 1000000.0)), os.getpid(), Maildir._count, hostname)) path = os.path.join(self._path, 'tmp', uniq) try: os.stat(path) except OSError as e: if (e.errno == errno.ENOENT): Maildir._count += 1 try: return _create_carefully(path) except OSError as e: if (e.errno != errno.EEXIST): raise else: raise raise ExternalClashError(('Name clash prevented file creation: %s' % path))
'Update table of contents mapping.'
def _refresh(self):
if ((time.time() - self._last_read) > (2 + self._skewfactor)): refresh = False for subdir in self._toc_mtimes: mtime = os.path.getmtime(self._paths[subdir]) if (mtime > self._toc_mtimes[subdir]): refresh = True self._toc_mtimes[subdir] = mtime if (not refresh): return self._toc = {} for subdir in self._toc_mtimes: path = self._paths[subdir] for entry in os.listdir(path): p = os.path.join(path, entry) if os.path.isdir(p): continue uniq = entry.split(self.colon)[0] self._toc[uniq] = os.path.join(subdir, entry) self._last_read = time.time()
'Use TOC to return subpath for given key, or raise a KeyError.'
def _lookup(self, key):
try: if os.path.exists(os.path.join(self._path, self._toc[key])): return self._toc[key] except KeyError: pass self._refresh() try: return self._toc[key] except KeyError: raise KeyError(('No message with key: %s' % key))
'Return the next message in a one-time iteration.'
def next(self):
if (not hasattr(self, '_onetime_keys')): self._onetime_keys = self.iterkeys() while True: try: return self[self._onetime_keys.next()] except StopIteration: return None except KeyError: continue
'Initialize a single-file mailbox.'
def __init__(self, path, factory=None, create=True):
Mailbox.__init__(self, path, factory, create) try: f = open(self._path, 'rb+') except IOError as e: if (e.errno == errno.ENOENT): if create: f = open(self._path, 'wb+') else: raise NoSuchMailboxError(self._path) elif (e.errno in (errno.EACCES, errno.EROFS)): f = open(self._path, 'rb') else: raise self._file = f self._toc = None self._next_key = 0 self._pending = False self._locked = False self._file_length = None
'Add message and return assigned key.'
def add(self, message):
self._lookup() self._toc[self._next_key] = self._append_message(message) self._next_key += 1 self._pending = True return (self._next_key - 1)
'Remove the keyed message; raise KeyError if it doesn\'t exist.'
def remove(self, key):
self._lookup(key) del self._toc[key] self._pending = True
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
def __setitem__(self, key, message):
self._lookup(key) self._toc[key] = self._append_message(message) self._pending = True
'Return an iterator over keys.'
def iterkeys(self):
self._lookup() for key in self._toc.keys(): (yield key)
'Return True if the keyed message exists, False otherwise.'
def has_key(self, key):
self._lookup() return (key in self._toc)
'Return a count of messages in the mailbox.'
def __len__(self):
self._lookup() return len(self._toc)
'Lock the mailbox.'
def lock(self):
if (not self._locked): _lock_file(self._file) self._locked = True
'Unlock the mailbox if it is locked.'
def unlock(self):
if self._locked: _unlock_file(self._file) self._locked = False
'Write any pending changes to disk.'
def flush(self):
if (not self._pending): return assert (self._toc is not None) self._file.seek(0, 2) cur_len = self._file.tell() if (cur_len != self._file_length): raise ExternalClashError(('Size of mailbox file changed (expected %i, found %i)' % (self._file_length, cur_len))) new_file = _create_temporary(self._path) try: new_toc = {} self._pre_mailbox_hook(new_file) for key in sorted(self._toc.keys()): (start, stop) = self._toc[key] self._file.seek(start) self._pre_message_hook(new_file) new_start = new_file.tell() while True: buffer = self._file.read(min(4096, (stop - self._file.tell()))) if (buffer == ''): break new_file.write(buffer) new_toc[key] = (new_start, new_file.tell()) self._post_message_hook(new_file) except: new_file.close() os.remove(new_file.name) raise _sync_close(new_file) self._file.close() try: os.rename(new_file.name, self._path) except OSError as e: if ((e.errno == errno.EEXIST) or ((os.name == 'os2') and (e.errno == errno.EACCES))): os.remove(self._path) os.rename(new_file.name, self._path) else: raise self._file = open(self._path, 'rb+') self._toc = new_toc self._pending = False if self._locked: _lock_file(self._file, dotlock=False)
'Called before writing the mailbox to file f.'
def _pre_mailbox_hook(self, f):
return
'Called before writing each message to file f.'
def _pre_message_hook(self, f):
return
'Called after writing each message to file f.'
def _post_message_hook(self, f):
return
'Flush and close the mailbox.'
def close(self):
self.flush() if self._locked: self.unlock() self._file.close()
'Return (start, stop) or raise KeyError.'
def _lookup(self, key=None):
if (self._toc is None): self._generate_toc() if (key is not None): try: return self._toc[key] except KeyError: raise KeyError(('No message with key: %s' % key))
'Append message to mailbox and return (start, stop) offsets.'
def _append_message(self, message):
self._file.seek(0, 2) before = self._file.tell() try: self._pre_message_hook(self._file) offsets = self._install_message(message) self._post_message_hook(self._file) except BaseException: self._file.truncate(before) raise self._file.flush() self._file_length = self._file.tell() return offsets
'Return a Message representation or raise a KeyError.'
def get_message(self, key):
(start, stop) = self._lookup(key) self._file.seek(start) from_line = self._file.readline().replace(os.linesep, '') string = self._file.read((stop - self._file.tell())) msg = self._message_factory(string.replace(os.linesep, '\n')) msg.set_from(from_line[5:]) return msg
'Return a string representation or raise a KeyError.'
def get_string(self, key, from_=False):
(start, stop) = self._lookup(key) self._file.seek(start) if (not from_): self._file.readline() string = self._file.read((stop - self._file.tell())) return string.replace(os.linesep, '\n')
'Return a file-like representation or raise a KeyError.'
def get_file(self, key, from_=False):
(start, stop) = self._lookup(key) self._file.seek(start) if (not from_): self._file.readline() return _PartialFile(self._file, self._file.tell(), stop)
'Format a message and blindly write to self._file.'
def _install_message(self, message):
from_line = None if (isinstance(message, str) and message.startswith('From ')): newline = message.find('\n') if (newline != (-1)): from_line = message[:newline] message = message[(newline + 1):] else: from_line = message message = '' elif isinstance(message, _mboxMMDFMessage): from_line = ('From ' + message.get_from()) elif isinstance(message, email.message.Message): from_line = message.get_unixfrom() if (from_line is None): from_line = ('From MAILER-DAEMON %s' % time.asctime(time.gmtime())) start = self._file.tell() self._file.write((from_line + os.linesep)) self._dump_message(message, self._file, self._mangle_from_) stop = self._file.tell() return (start, stop)
'Initialize an mbox mailbox.'
def __init__(self, path, factory=None, create=True):
self._message_factory = mboxMessage _mboxMMDF.__init__(self, path, factory, create)
'Called before writing each message to file f.'
def _pre_message_hook(self, f):
if (f.tell() != 0): f.write(os.linesep)
'Generate key-to-(start, stop) table of contents.'
def _generate_toc(self):
(starts, stops) = ([], []) self._file.seek(0) while True: line_pos = self._file.tell() line = self._file.readline() if line.startswith('From '): if (len(stops) < len(starts)): stops.append((line_pos - len(os.linesep))) starts.append(line_pos) elif (line == ''): stops.append(line_pos) break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) self._file_length = self._file.tell()
'Initialize an MMDF mailbox.'
def __init__(self, path, factory=None, create=True):
self._message_factory = MMDFMessage _mboxMMDF.__init__(self, path, factory, create)
'Called before writing each message to file f.'
def _pre_message_hook(self, f):
f.write(('\x01\x01\x01\x01' + os.linesep))
'Called after writing each message to file f.'
def _post_message_hook(self, f):
f.write(((os.linesep + '\x01\x01\x01\x01') + os.linesep))
'Generate key-to-(start, stop) table of contents.'
def _generate_toc(self):
(starts, stops) = ([], []) self._file.seek(0) next_pos = 0 while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line.startswith(('\x01\x01\x01\x01' + os.linesep)): starts.append(next_pos) while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if (line == ('\x01\x01\x01\x01' + os.linesep)): stops.append((line_pos - len(os.linesep))) break elif (line == ''): stops.append(line_pos) break elif (line == ''): break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) self._file.seek(0, 2) self._file_length = self._file.tell()
'Initialize an MH instance.'
def __init__(self, path, factory=None, create=True):
Mailbox.__init__(self, path, factory, create) if (not os.path.exists(self._path)): if create: os.mkdir(self._path, 448) os.close(os.open(os.path.join(self._path, '.mh_sequences'), ((os.O_CREAT | os.O_EXCL) | os.O_WRONLY), 384)) else: raise NoSuchMailboxError(self._path) self._locked = False
'Add message and return assigned key.'
def add(self, message):
keys = self.keys() if (len(keys) == 0): new_key = 1 else: new_key = (max(keys) + 1) new_path = os.path.join(self._path, str(new_key)) f = _create_carefully(new_path) closed = False try: if self._locked: _lock_file(f) try: try: self._dump_message(message, f) except BaseException: if self._locked: _unlock_file(f) _sync_close(f) closed = True os.remove(new_path) raise if isinstance(message, MHMessage): self._dump_sequences(message, new_key) finally: if self._locked: _unlock_file(f) finally: if (not closed): _sync_close(f) return new_key
'Remove the keyed message; raise KeyError if it doesn\'t exist.'
def remove(self, key):
path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except IOError as e: if (e.errno == errno.ENOENT): raise KeyError(('No message with key: %s' % key)) else: raise else: f.close() os.remove(path)
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
def __setitem__(self, key, message):
path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except IOError as e: if (e.errno == errno.ENOENT): raise KeyError(('No message with key: %s' % key)) else: raise try: if self._locked: _lock_file(f) try: os.close(os.open(path, (os.O_WRONLY | os.O_TRUNC))) self._dump_message(message, f) if isinstance(message, MHMessage): self._dump_sequences(message, key) finally: if self._locked: _unlock_file(f) finally: _sync_close(f)
'Return a Message representation or raise a KeyError.'
def get_message(self, key):
try: if self._locked: f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') except IOError as e: if (e.errno == errno.ENOENT): raise KeyError(('No message with key: %s' % key)) else: raise try: if self._locked: _lock_file(f) try: msg = MHMessage(f) finally: if self._locked: _unlock_file(f) finally: f.close() for (name, key_list) in self.get_sequences().iteritems(): if (key in key_list): msg.add_sequence(name) return msg
'Return a string representation or raise a KeyError.'
def get_string(self, key):
try: if self._locked: f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') except IOError as e: if (e.errno == errno.ENOENT): raise KeyError(('No message with key: %s' % key)) else: raise try: if self._locked: _lock_file(f) try: return f.read() finally: if self._locked: _unlock_file(f) finally: f.close()