summaryrefslogtreecommitdiffstats
path: root/Lib/rfc822.py
diff options
context:
space:
mode:
authorTim Peters <tim.peters@gmail.com>2001-01-15 01:18:21 (GMT)
committerTim Peters <tim.peters@gmail.com>2001-01-15 01:18:21 (GMT)
commit0c9886d589ddebf32de0ca3f027a173222ed383a (patch)
tree8d18864b0026ee37a1e917bbb0ff93a1bebda309 /Lib/rfc822.py
parent2344fae6d003f5a5dde8016e1d2310e161288708 (diff)
downloadcpython-0c9886d589ddebf32de0ca3f027a173222ed383a.zip
cpython-0c9886d589ddebf32de0ca3f027a173222ed383a.tar.gz
cpython-0c9886d589ddebf32de0ca3f027a173222ed383a.tar.bz2
Whitespace normalization.
Diffstat (limited to 'Lib/rfc822.py')
-rw-r--r--Lib/rfc822.py166
1 files changed, 83 insertions, 83 deletions
diff --git a/Lib/rfc822.py b/Lib/rfc822.py
index 782054b..89de69a 100644
--- a/Lib/rfc822.py
+++ b/Lib/rfc822.py
@@ -28,7 +28,7 @@ portability, you should set the seekable argument to zero to prevent
that initial \code{tell} when passing in an unseekable object such as
a a file object created from a socket object. If it is 1 on entry --
which it is by default -- the tell() method of the open file object is
-called once; if this raises an exception, seekable is reset to 0. For
+called once; if this raises an exception, seekable is reset to 0. For
other nonzero values of seekable, this test is not made.
To get the text of a particular header there are several methods:
@@ -65,7 +65,7 @@ _blanklines = ('\r\n', '\n') # Optimization for islast()
class Message:
"""Represents a single RFC-822-compliant message."""
-
+
def __init__(self, fp, seekable = 1):
"""Initialize the class instance and read the headers."""
if seekable == 1:
@@ -95,23 +95,23 @@ class Message:
self.startofbody = self.fp.tell()
except IOError:
self.seekable = 0
-
+
def rewindbody(self):
"""Rewind the file to the start of the body (if seekable)."""
if not self.seekable:
raise IOError, "unseekable file"
self.fp.seek(self.startofbody)
-
+
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
@@ -190,15 +190,15 @@ class Message:
return line[:i].lower()
else:
return None
-
+
def islast(self, line):
"""Determine whether a line is a legal end of RFC-822 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.
+ line consisting of \r\n also matches.
"""
return line in _blanklines
@@ -210,10 +210,10 @@ class Message:
comments or free-text data.
"""
return None
-
+
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
@@ -234,10 +234,10 @@ class Message:
if hit:
list.append(line)
return list
-
+
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).
@@ -255,26 +255,26 @@ class Message:
if hit:
list.append(line)
return list
-
+
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.
"""
-
+
list = self.getfirstmatchingheader(name)
if not list:
return None
list[0] = list[0][len(name) + 1:]
return ''.join(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
@@ -311,10 +311,10 @@ class Message:
if have_header:
result.append(current)
return result
-
+
def getaddr(self, name):
"""Get a single address from a header, as a tuple.
-
+
An example return value:
('Guido van Rossum', 'guido@cwi.nl')
"""
@@ -324,7 +324,7 @@ class Message:
return alist[0]
else:
return (None, None)
-
+
def getaddrlist(self, name):
"""Get a list of addresses from a header.
@@ -347,10 +347,10 @@ class Message:
alladdrs = ''.join(raw)
a = AddrlistClass(alladdrs)
return a.getaddrlist()
-
+
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().
"""
@@ -359,10 +359,10 @@ class Message:
except KeyError:
return None
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.
@@ -372,14 +372,14 @@ class Message:
except KeyError:
return None
return parsedate_tz(data)
-
-
+
+
# Access as a dictionary (only finds *last* header of each type):
-
+
def __len__(self):
"""Get the number of headers in a message."""
return len(self.dict)
-
+
def __getitem__(self, name):
"""Get a specific header, as from a dictionary."""
return self.dict[name.lower()]
@@ -387,7 +387,7 @@ class Message:
def __setitem__(self, name, value):
"""Set the value of a header.
- Note: This is not a perfect inversion of __getitem__, because
+ 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.
"""
@@ -397,7 +397,7 @@ class Message:
lines = text.split("\n")
for line in lines:
self.headers.append(line + "\n")
-
+
def __delitem__(self, name):
"""Delete all occurrences of a specific header, if it is present."""
name = name.lower()
@@ -423,18 +423,18 @@ class Message:
def has_key(self, name):
"""Determine whether a message contains the named header."""
return self.dict.has_key(name.lower())
-
+
def keys(self):
"""Get all of a message's header field names."""
return self.dict.keys()
-
+
def values(self):
"""Get all of a message's header field values."""
return self.dict.values()
-
+
def items(self):
"""Get all of a message's headers.
-
+
Returns a list of name, value tuples.
"""
return self.dict.items()
@@ -480,17 +480,17 @@ def parseaddr(address):
class AddrlistClass:
"""Address parser class by Ben Escoto.
-
+
To understand what this class does, it helps to have a copy of
RFC-822 in front of you.
Note: this class interface is deprecated and may be removed in the future.
Use rfc822.AddressList instead.
"""
-
+
def __init__(self, field):
"""Initialize a new instance.
-
+
`field' is an unparsed address header field, containing
one or more addresses.
"""
@@ -501,7 +501,7 @@ class AddrlistClass:
self.atomends = self.specials + self.LWS + self.CR
self.field = field
self.commentlist = []
-
+
def gotonext(self):
"""Parse up to the start of the next address."""
while self.pos < len(self.field):
@@ -510,34 +510,34 @@ class AddrlistClass:
elif self.field[self.pos] == '(':
self.commentlist.append(self.getcomment())
else: break
-
+
def getaddrlist(self):
"""Parse all addresses.
-
+
Returns a list containing all of the addresses.
"""
ad = self.getaddress()
if ad:
return ad + self.getaddrlist()
else: return []
-
+
def getaddress(self):
"""Parse the next address."""
self.commentlist = []
self.gotonext()
-
+
oldpos = self.pos
oldcl = self.commentlist
plist = self.getphraselist()
-
+
self.gotonext()
returnlist = []
-
+
if self.pos >= len(self.field):
# Bad email address technically, no domain.
if plist:
returnlist = [(' '.join(self.commentlist), plist[0])]
-
+
elif self.field[self.pos] in '.@':
# email address is just an addrspec
# this isn't very efficient since we start over
@@ -545,11 +545,11 @@ class AddrlistClass:
self.commentlist = oldcl
addrspec = self.getaddrspec()
returnlist = [(' '.join(self.commentlist), addrspec)]
-
+
elif self.field[self.pos] == ':':
# address is a group
returnlist = []
-
+
fieldlen = len(self.field)
self.pos = self.pos + 1
while self.pos < len(self.field):
@@ -558,35 +558,35 @@ class AddrlistClass:
self.pos = self.pos + 1
break
returnlist = returnlist + self.getaddress()
-
+
elif self.field[self.pos] == '<':
# Address is a phrase then a route addr
routeaddr = self.getrouteaddr()
-
+
if self.commentlist:
returnlist = [(' '.join(plist) + ' (' + \
' '.join(self.commentlist) + ')', routeaddr)]
else: returnlist = [(' '.join(plist), routeaddr)]
-
+
else:
if plist:
returnlist = [(' '.join(self.commentlist), plist[0])]
elif self.field[self.pos] in self.specials:
self.pos = self.pos + 1
-
+
self.gotonext()
if self.pos < len(self.field) and self.field[self.pos] == ',':
self.pos = self.pos + 1
return returnlist
-
+
def getrouteaddr(self):
"""Parse a route address (Return-path value).
-
+
This method just skips all the route stuff and returns the addrspec.
"""
if self.field[self.pos] != '<':
return
-
+
expectroute = 0
self.pos = self.pos + 1
self.gotonext()
@@ -609,13 +609,13 @@ class AddrlistClass:
self.pos = self.pos + 1
break
self.gotonext()
-
+
return adlist
-
+
def getaddrspec(self):
"""Parse an RFC-822 addr-spec."""
aslist = []
-
+
self.gotonext()
while self.pos < len(self.field):
if self.field[self.pos] == '.':
@@ -627,15 +627,15 @@ class AddrlistClass:
break
else: aslist.append(self.getatom())
self.gotonext()
-
+
if self.pos >= len(self.field) or self.field[self.pos] != '@':
return ''.join(aslist)
-
+
aslist.append('@')
self.pos = self.pos + 1
self.gotonext()
return ''.join(aslist) + self.getdomain()
-
+
def getdomain(self):
"""Get the complete domain name from an address."""
sdlist = []
@@ -653,23 +653,23 @@ class AddrlistClass:
break
else: sdlist.append(self.getatom())
return ''.join(sdlist)
-
+
def getdelimited(self, beginchar, endchars, allowcomments = 1):
"""Parse a header fragment delimited by special characters.
-
+
`beginchar' is the start character for the fragment.
If self is not looking at an instance of `beginchar' then
getdelimited returns the empty string.
-
+
`endchars' is a sequence of allowable end-delimiting characters.
Parsing stops when one of these is encountered.
-
+
If `allowcomments' is non-zero, embedded RFC-822 comments
are allowed within the parsed fragment.
"""
if self.field[self.pos] != beginchar:
return ''
-
+
slist = ['']
quote = 0
self.pos = self.pos + 1
@@ -687,42 +687,42 @@ class AddrlistClass:
else:
slist.append(self.field[self.pos])
self.pos = self.pos + 1
-
+
return ''.join(slist)
-
+
def getquote(self):
"""Get a quote-delimited fragment from self's field."""
return self.getdelimited('"', '"\r', 0)
-
+
def getcomment(self):
"""Get a parenthesis-delimited fragment from self's field."""
return self.getdelimited('(', ')\r', 1)
-
+
def getdomainliteral(self):
"""Parse an RFC-822 domain-literal."""
return '[%s]' % self.getdelimited('[', ']\r', 0)
-
+
def getatom(self):
"""Parse an RFC-822 atom."""
atomlist = ['']
-
+
while self.pos < len(self.field):
if self.field[self.pos] in self.atomends:
break
else: atomlist.append(self.field[self.pos])
self.pos = self.pos + 1
-
+
return ''.join(atomlist)
-
+
def getphraselist(self):
"""Parse a sequence of RFC-822 phrases.
-
+
A phrase is a sequence of words, which are in turn either
RFC-822 atoms or quoted-strings. Phrases are canonicalized
by squeezing all runs of continuous whitespace into one space.
"""
plist = []
-
+
while self.pos < len(self.field):
if self.field[self.pos] in self.LWS:
self.pos = self.pos + 1
@@ -733,7 +733,7 @@ class AddrlistClass:
elif self.field[self.pos] in self.atomends:
break
else: plist.append(self.getatom())
-
+
return plist
class AddressList(AddrlistClass):
@@ -807,18 +807,18 @@ _daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
# zones. RFC1123 recommends that numeric timezone indicators be used
# instead of timezone names.
-_timezones = {'UT':0, 'UTC':0, 'GMT':0, 'Z':0,
+_timezones = {'UT':0, 'UTC':0, 'GMT':0, 'Z':0,
'AST': -400, 'ADT': -300, # Atlantic (used in Canada)
'EST': -500, 'EDT': -400, # Eastern
'CST': -600, 'CDT': -500, # Central
'MST': -700, 'MDT': -600, # Mountain
'PST': -800, 'PDT': -700 # Pacific
- }
+ }
def parsedate_tz(data):
"""Convert a date string to a time tuple.
-
+
Accounts for military timezones.
"""
data = data.split()
@@ -879,9 +879,9 @@ def parsedate_tz(data):
if _timezones.has_key(tz):
tzoffset = _timezones[tz]
else:
- try:
+ try:
tzoffset = int(tz)
- except ValueError:
+ except ValueError:
pass
# Convert a timezone offset into seconds ; -0500 -> -18000
if tzoffset:
@@ -900,7 +900,7 @@ def parsedate(data):
t = parsedate_tz(data)
if type(t) == type( () ):
return t[:9]
- else: return t
+ else: return t
def mktime_tz(data):