Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
•All Data Structures Namespaces Files Functions Variables
Message Class Reference
Inheritance diagram for Message:
Message Message SubMessage

Public Member Functions

def __init__
 
def rewindbody
 
def readheaders
 
def isheader
 
def islast
 
def iscomment
 
def getallmatchingheaders
 
def getfirstmatchingheader
 
def getrawheader
 
def getheader
 
def getheaders
 
def getaddr
 
def getaddrlist
 
def getdate
 
def getdate_tz
 
def __len__
 
def __getitem__
 
def __setitem__
 
def __delitem__
 
def get
 
def setdefault
 
def has_key
 
def keys
 
def values
 
def items
 
def __str__
 

Data Fields

 fp
 
 seekable
 
 startofheaders
 
 startofbody
 
 dict
 
 unixfrom
 
 headers
 
 status
 

Static Public Attributes

 get = getheader
 

Detailed Description

Represents a single RFC 2822-compliant message.

Definition at line 81 of file rfc822.py.

Constructor & Destructor Documentation

def __init__ (   self,
  fp,
  seekable = 1 
)
Initialize the class instance and read the headers.

Definition at line 84 of file rfc822.py.

References Message.headers.

84 
85  def __init__(self, fp, seekable = 1):
86  """Initialize the class instance and read the headers."""
87  if seekable == 1:
88  # Exercise tell() to make sure it works
89  # (and then assume seek() works, too)
90  try:
91  fp.tell()
92  except (AttributeError, IOError):
93  seekable = 0
94  else:
95  seekable = 1
96  self.fp = fp
97  self.seekable = seekable
98  self.startofheaders = None
99  self.startofbody = None
100  #
101  if self.seekable:
102  try:
103  self.startofheaders = self.fp.tell()
104  except IOError:
105  self.seekable = 0
106  #
107  self.readheaders()
108  #
109  if self.seekable:
110  try:
111  self.startofbody = self.fp.tell()
112  except IOError:
113  self.seekable = 0

Member Function Documentation

def __delitem__ (   self,
  name 
)
Delete all occurrences of a specific header, if it is present.

Definition at line 406 of file rfc822.py.

407  def __delitem__(self, name):
408  """Delete all occurrences of a specific header, if it is present."""
409  name = name.lower()
410  if not self.dict.has_key(name):
411  return
412  del self.dict[name]
413  name = name + ':'
414  n = len(name)
415  list = []
416  hit = 0
417  for i in range(len(self.headers)):
418  line = self.headers[i]
419  if line[:n].lower() == name:
420  hit = 1
421  elif not line[:1].isspace():
422  hit = 0
423  if hit:
424  list.append(i)
425  list.reverse()
426  for i in list:
427  del self.headers[i]
def __getitem__ (   self,
  name 
)
Get a specific header, as from a dictionary.

Definition at line 388 of file rfc822.py.

389  def __getitem__(self, name):
390  """Get a specific header, as from a dictionary."""
391  return self.dict[name.lower()]
def __len__ (   self)
Get the number of headers in a message.

Definition at line 384 of file rfc822.py.

385  def __len__(self):
386  """Get the number of headers in a message."""
387  return len(self.dict)
def __setitem__ (   self,
  name,
  value 
)
Set the value of a header.

Note: This is not a perfect inversion of __getitem__, because any
changed headers get stuck at the end of the raw-headers list rather
than where the altered header was.

Definition at line 392 of file rfc822.py.

393  def __setitem__(self, name, value):
394  """Set the value of a header.
395 
396  Note: This is not a perfect inversion of __getitem__, because any
397  changed headers get stuck at the end of the raw-headers list rather
398  than where the altered header was.
399  """
400  del self[name] # Won't fail if it doesn't exist
401  self.dict[name.lower()] = value
402  text = name + ": " + value
403  lines = text.split("\n")
404  for line in lines:
405  self.headers.append(line + "\n")
def __str__ (   self)

Definition at line 466 of file rfc822.py.

References Message.headers, BaseHTTPRequestHandler.headers, MiniFieldStorage.headers, FieldStorage.headers, and HTTP.headers.

467  def __str__(self):
468  str = ''
469  for hdr in self.headers:
470  str = str + hdr
471  return str
472 
473 
474 # Utility functions
475 # -----------------
476 
477 # XXX Should fix unquote() and quote() to be really conformant.
478 # XXX The inverses of the parse functions may also be useful.
479 
def get (   self,
  name,
  default = "" 
)

Definition at line 428 of file rfc822.py.

429  def get(self, name, default=""):
430  name = name.lower()
431  if self.dict.has_key(name):
432  return self.dict[name]
433  else:
434  return default
def getaddr (   self,
  name 
)
Get a single address from a header, as a tuple.

An example return value:
('Guido van Rossum', 'guido@cwi.nl')

Definition at line 322 of file rfc822.py.

323  def getaddr(self, name):
324  """Get a single address from a header, as a tuple.
325 
326  An example return value:
327  ('Guido van Rossum', 'guido@cwi.nl')
328  """
329  # New, by Ben Escoto
330  alist = self.getaddrlist(name)
331  if alist:
332  return alist[0]
333  else:
334  return (None, None)
def getaddrlist (   self,
  name 
)
Get a list of addresses from a header.

Retrieves a list of addresses from a header, where each address is a
tuple as returned by getaddr().  Scans all named headers, so it works
properly with multiple To: or Cc: headers for example.

Definition at line 335 of file rfc822.py.

References Message.getaddr().

336  def getaddrlist(self, name):
337  """Get a list of addresses from a header.
338 
339  Retrieves a list of addresses from a header, where each address is a
340  tuple as returned by getaddr(). Scans all named headers, so it works
341  properly with multiple To: or Cc: headers for example.
342  """
343  raw = []
344  for h in self.getallmatchingheaders(name):
345  if h[0] in ' \t':
346  raw.append(h)
347  else:
348  if raw:
349  raw.append(', ')
350  i = h.find(':')
351  if i > 0:
352  addr = h[i+1:]
353  raw.append(addr)
354  alladdrs = ''.join(raw)
355  a = AddrlistClass(alladdrs)
356  return a.getaddrlist()
def getallmatchingheaders (   self,
  name 
)
Find all header lines matching a given header name.

Look through the list of headers and find all lines matching a given
header name (and their continuation lines).  A list of the lines is
returned, without interpretation.  If the header does not occur, an
empty list is returned.  If the header occurs multiple times, all
occurrences are returned.  Case is not important in the header name.

Definition at line 227 of file rfc822.py.

228  def getallmatchingheaders(self, name):
229  """Find all header lines matching a given header name.
230 
231  Look through the list of headers and find all lines matching a given
232  header name (and their continuation lines). A list of the lines is
233  returned, without interpretation. If the header does not occur, an
234  empty list is returned. If the header occurs multiple times, all
235  occurrences are returned. Case is not important in the header name.
236  """
237  name = name.lower() + ':'
238  n = len(name)
239  list = []
240  hit = 0
241  for line in self.headers:
242  if line[:n].lower() == name:
243  hit = 1
244  elif not line[:1].isspace():
245  hit = 0
246  if hit:
247  list.append(line)
248  return list
def getdate (   self,
  name 
)
Retrieve a date field from a header.

Retrieves a date field from the named header, returning a tuple
compatible with time.mktime().

Definition at line 357 of file rfc822.py.

358  def getdate(self, name):
359  """Retrieve a date field from a header.
360 
361  Retrieves a date field from the named header, returning a tuple
362  compatible with time.mktime().
363  """
364  try:
365  data = self[name]
366  except KeyError:
367  return None
368  return parsedate(data)
def getdate_tz (   self,
  name 
)
Retrieve a date field from a header as a 10-tuple.

The first 9 elements make up a tuple compatible with time.mktime(),
and the 10th is the offset of the poster's time zone from GMT/UTC.

Definition at line 369 of file rfc822.py.

370  def getdate_tz(self, name):
371  """Retrieve a date field from a header as a 10-tuple.
372 
373  The first 9 elements make up a tuple compatible with time.mktime(),
374  and the 10th is the offset of the poster's time zone from GMT/UTC.
375  """
376  try:
377  data = self[name]
378  except KeyError:
379  return None
380  return parsedate_tz(data)
381 
def getfirstmatchingheader (   self,
  name 
)
Get the first header line matching name.

This is similar to getallmatchingheaders, but it returns only the
first matching header (and its continuation lines).

Definition at line 249 of file rfc822.py.

250  def getfirstmatchingheader(self, name):
251  """Get the first header line matching name.
252 
253  This is similar to getallmatchingheaders, but it returns only the
254  first matching header (and its continuation lines).
255  """
256  name = name.lower() + ':'
257  n = len(name)
258  list = []
259  hit = 0
260  for line in self.headers:
261  if hit:
262  if not line[:1].isspace():
263  break
264  elif line[:n].lower() == name:
265  hit = 1
266  if hit:
267  list.append(line)
268  return list
def getheader (   self,
  name,
  default = None 
)
Get the header value for a name.

This is the normal interface: it returns a stripped version of the
header value for a given header name, or None if it doesn't exist.
This uses the dictionary version which finds the *last* such header.

Definition at line 284 of file rfc822.py.

285  def getheader(self, name, default=None):
286  """Get the header value for a name.
287 
288  This is the normal interface: it returns a stripped version of the
289  header value for a given header name, or None if it doesn't exist.
290  This uses the dictionary version which finds the *last* such header.
291  """
292  try:
293  return self.dict[name.lower()]
294  except KeyError:
return default
def getheaders (   self,
  name 
)
Get all values for a header.

This returns a list of values for headers given more than once; each
value in the result list is stripped in the same way as the result of
getheader().  If the header is not given, return an empty list.

Definition at line 297 of file rfc822.py.

References Message.getheader().

298  def getheaders(self, name):
299  """Get all values for a header.
300 
301  This returns a list of values for headers given more than once; each
302  value in the result list is stripped in the same way as the result of
303  getheader(). If the header is not given, return an empty list.
304  """
305  result = []
306  current = ''
307  have_header = 0
308  for s in self.getallmatchingheaders(name):
309  if s[0].isspace():
310  if current:
311  current = "%s\n %s" % (current, s.strip())
312  else:
313  current = s.strip()
314  else:
315  if have_header:
316  result.append(current)
317  current = s[s.find(":") + 1:].strip()
318  have_header = 1
319  if have_header:
320  result.append(current)
321  return result
def getrawheader (   self,
  name 
)
A higher-level interface to getfirstmatchingheader().

Return a string containing the literal text of the header but with the
keyword stripped.  All leading, trailing and embedded whitespace is
kept in the string, however.  Return None if the header does not
occur.

Definition at line 269 of file rfc822.py.

References Message.getfirstmatchingheader().

270  def getrawheader(self, name):
271  """A higher-level interface to getfirstmatchingheader().
272 
273  Return a string containing the literal text of the header but with the
274  keyword stripped. All leading, trailing and embedded whitespace is
275  kept in the string, however. Return None if the header does not
276  occur.
277  """
278 
279  list = self.getfirstmatchingheader(name)
280  if not list:
281  return None
282  list[0] = list[0][len(name) + 1:]
283  return ''.join(list)
def has_key (   self,
  name 
)
Determine whether a message contains the named header.

Definition at line 447 of file rfc822.py.

448  def has_key(self, name):
449  """Determine whether a message contains the named header."""
450  return self.dict.has_key(name.lower())
def iscomment (   self,
  line 
)
Determine whether a line should be skipped entirely.

You may override this method in order to use Message parsing on tagged
data in RFC 2822-like formats that support embedded comments or
free-text data.

Definition at line 218 of file rfc822.py.

219  def iscomment(self, line):
220  """Determine whether a line should be skipped entirely.
221 
222  You may override this method in order to use Message parsing on tagged
223  data in RFC 2822-like formats that support embedded comments or
224  free-text data.
225  """
226  return None
def isheader (   self,
  line 
)
Determine whether a given line is a legal header.

This method should return the header name, suitably canonicalized.
You may override this method in order to use Message parsing on tagged
data in RFC 2822-like formats with special header formats.

Definition at line 195 of file rfc822.py.

196  def isheader(self, line):
197  """Determine whether a given line is a legal header.
198 
199  This method should return the header name, suitably canonicalized.
200  You may override this method in order to use Message parsing on tagged
201  data in RFC 2822-like formats with special header formats.
202  """
203  i = line.find(':')
204  if i > 0:
205  return line[:i].lower()
206  else:
207  return None
def islast (   self,
  line 
)
Determine whether a line is a legal end of RFC 2822 headers.

You may override this method if your application wants to bend the
rules, e.g. to strip trailing whitespace, or to recognize MH template
separators ('--------').  For convenience (e.g. for code reading from
sockets) a line consisting of \r\n also matches.

Definition at line 208 of file rfc822.py.

209  def islast(self, line):
210  """Determine whether a line is a legal end of RFC 2822 headers.
211 
212  You may override this method if your application wants to bend the
213  rules, e.g. to strip trailing whitespace, or to recognize MH template
214  separators ('--------'). For convenience (e.g. for code reading from
215  sockets) a line consisting of \r\n also matches.
216  """
217  return line in _blanklines
def items (   self)
Get all of a message's headers.

Returns a list of name, value tuples.

Definition at line 459 of file rfc822.py.

460  def items(self):
461  """Get all of a message's headers.
462 
463  Returns a list of name, value tuples.
464  """
465  return self.dict.items()
def keys (   self)
Get all of a message's header field names.

Definition at line 451 of file rfc822.py.

452  def keys(self):
453  """Get all of a message's header field names."""
454  return self.dict.keys()
def readheaders (   self)
Read header lines.

Read header lines up to the entirely blank line that terminates them.
The (normally blank) line that ends the headers is skipped, but not
included in the returned list.  If a non-header line ends the headers,
(which is an error), an attempt is made to backspace over it; it is
never included in the returned list.

The variable self.status is set to the empty string if all went well,
otherwise it is an error message.  The variable self.headers is a
completely uninterpreted list of lines contained in the header (so
printing them will reproduce the header exactly as it appears in the
file).

Definition at line 120 of file rfc822.py.

References Message.headers, BaseHTTPRequestHandler.headers, MiniFieldStorage.headers, FieldStorage.headers, HTTP.headers, HTTPResponse.status, and Message.status.

121  def readheaders(self):
122  """Read header lines.
123 
124  Read header lines up to the entirely blank line that terminates them.
125  The (normally blank) line that ends the headers is skipped, but not
126  included in the returned list. If a non-header line ends the headers,
127  (which is an error), an attempt is made to backspace over it; it is
128  never included in the returned list.
129 
130  The variable self.status is set to the empty string if all went well,
131  otherwise it is an error message. The variable self.headers is a
132  completely uninterpreted list of lines contained in the header (so
133  printing them will reproduce the header exactly as it appears in the
134  file).
135  """
136  self.dict = {}
137  self.unixfrom = ''
138  self.headers = list = []
139  self.status = ''
140  headerseen = ""
141  firstline = 1
142  startofline = unread = tell = None
143  if hasattr(self.fp, 'unread'):
144  unread = self.fp.unread
145  elif self.seekable:
146  tell = self.fp.tell
147  while 1:
148  if tell:
149  try:
150  startofline = tell()
151  except IOError:
152  startofline = tell = None
153  self.seekable = 0
154  line = self.fp.readline()
155  if not line:
156  self.status = 'EOF in headers'
157  break
158  # Skip unix From name time lines
159  if firstline and line.startswith('From '):
160  self.unixfrom = self.unixfrom + line
161  continue
162  firstline = 0
163  if headerseen and line[0] in ' \t':
164  # It's a continuation line.
165  list.append(line)
166  x = (self.dict[headerseen] + "\n " + line.strip())
167  self.dict[headerseen] = x.strip()
168  continue
169  elif self.iscomment(line):
170  # It's a comment. Ignore it.
171  continue
172  elif self.islast(line):
173  # Note! No pushback here! The delimiter line gets eaten.
174  break
175  headerseen = self.isheader(line)
176  if headerseen:
177  # It's a legal header line, save it.
178  list.append(line)
179  self.dict[headerseen] = line[len(headerseen)+1:].strip()
180  continue
181  else:
182  # It's not a header line; throw it back and stop here.
183  if not self.dict:
184  self.status = 'No headers'
185  else:
186  self.status = 'Non-header line where header expected'
187  # Try to undo the read.
188  if unread:
189  unread(line)
190  elif tell:
191  self.fp.seek(startofline)
192  else:
193  self.status = self.status + '; bad seek'
194  break
def rewindbody (   self)
Rewind the file to the start of the body (if seekable).

Definition at line 114 of file rfc822.py.

115  def rewindbody(self):
116  """Rewind the file to the start of the body (if seekable)."""
117  if not self.seekable:
118  raise IOError, "unseekable file"
119  self.fp.seek(self.startofbody)
def setdefault (   self,
  name,
  default = "" 
)

Definition at line 435 of file rfc822.py.

436  def setdefault(self, name, default=""):
437  lowername = name.lower()
438  if self.dict.has_key(lowername):
439  return self.dict[lowername]
440  else:
441  text = name + ": " + default
442  lines = text.split("\n")
443  for line in lines:
444  self.headers.append(line + "\n")
445  self.dict[lowername] = default
446  return default
def values (   self)
Get all of a message's header field values.

Definition at line 455 of file rfc822.py.

456  def values(self):
457  """Get all of a message's header field values."""
458  return self.dict.values()

Field Documentation

dict

Definition at line 135 of file rfc822.py.

fp

Definition at line 95 of file rfc822.py.

get = getheader
static

Definition at line 295 of file rfc822.py.

headers

Definition at line 137 of file rfc822.py.

seekable

Definition at line 96 of file rfc822.py.

startofbody

Definition at line 98 of file rfc822.py.

startofheaders

Definition at line 97 of file rfc822.py.

status

Definition at line 138 of file rfc822.py.

unixfrom

Definition at line 136 of file rfc822.py.


The documentation for this class was generated from the following file: