desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard\' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed.'
def flatten(self, msg, unixfrom=False):
if unixfrom: ufrom = msg.get_unixfrom() if (not ufrom): ufrom = ('From nobody ' + time.ctime(time.time())) print >>self._fp, ufrom self._write(msg)
'Clone this generator with the exact same options.'
def clone(self, fp):
return self.__class__(fp, self._mangle_from_, self._maxheaderlen)
'Like Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text\', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the following keywords (in %(keyword)s format): type : Full MIME type of the non-text part maintype : Main MIME type of the non-text part subtype : Sub-MIME type of the non-text part filename : Filename of the non-text part description: Description associated with the non-text part encoding : Content transfer encoding of the non-text part The default value for fmt is None, meaning [Non-text (%(type)s) part of message omitted, filename %(filename)s]'
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None):
Generator.__init__(self, outfp, mangle_from_, maxheaderlen) if (fmt is None): self._fmt = _FMT else: self._fmt = fmt
'Parser of RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the textual representation of the message. The string must be formatted as a block of RFC 2822 headers and header continuation lines, optionally preceded by a `Unix-from\' header. The header block is terminated either by the end of the string or by a blank line. _class is the class to instantiate for new message objects when they must be created. This class must have a constructor that can take zero arguments. Default is Message.Message.'
def __init__(self, *args, **kws):
if (len(args) >= 1): if ('_class' in kws): raise TypeError("Multiple values for keyword arg '_class'") kws['_class'] = args[0] if (len(args) == 2): if ('strict' in kws): raise TypeError("Multiple values for keyword arg 'strict'") kws['strict'] = args[1] if (len(args) > 2): raise TypeError('Too many arguments') if ('_class' in kws): self._class = kws['_class'] del kws['_class'] else: self._class = Message if ('strict' in kws): warnings.warn("'strict' argument is deprecated (and ignored)", DeprecationWarning, 2) del kws['strict'] if kws: raise TypeError('Unexpected keyword arguments')
'Create a message structure from the data in a file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file.'
def parse(self, fp, headersonly=False):
feedparser = FeedParser(self._class) if headersonly: feedparser._set_headersonly() while True: data = fp.read(8192) if (not data): break feedparser.feed(data) return feedparser.close()
'Create a message structure from a string. Returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file.'
def parsestr(self, text, headersonly=False):
return self.parse(StringIO(text), headersonly=headersonly)
'Push some new data into this object.'
def push(self, data):
parts = data.splitlines(True) if ((not parts) or (not parts[0].endswith(('\n', '\r')))): self._partial += parts return if self._partial: self._partial.append(parts[0]) parts[0:1] = ''.join(self._partial).splitlines(True) del self._partial[:] if (not parts[(-1)].endswith('\n')): self._partial = [parts.pop()] self.pushlines(parts)
'_factory is called with no arguments to create a new message obj'
def __init__(self, _factory=message.Message):
self._factory = _factory self._input = BufferedSubFile() self._msgstack = [] self._parse = self._parsegen().next self._cur = None self._last = None self._headersonly = False
'Push more data into the parser.'
def feed(self, data):
self._input.push(data) self._call_parse()
'Parse all remaining data and return the root message object.'
def close(self):
self._input.close() self._call_parse() root = self._pop_message() assert (not self._msgstack) if ((root.get_content_maintype() == 'multipart') and (not root.is_multipart())): root.defects.append(errors.MultipartInvariantViolationDefect()) return root
'Initialize a new instance. `field\' is an unparsed address header field, containing one or more addresses.'
def __init__(self, field):
self.specials = '()<>@,:;."[]' self.pos = 0 self.LWS = ' DCTB ' self.CR = '\r\n' self.FWS = (self.LWS + self.CR) self.atomends = ((self.specials + self.LWS) + self.CR) self.phraseends = self.atomends.replace('.', '') self.field = field self.commentlist = []
'Parse up to the start of the next address.'
def gotonext(self):
while (self.pos < len(self.field)): if (self.field[self.pos] in (self.LWS + '\n\r')): self.pos += 1 elif (self.field[self.pos] == '('): self.commentlist.append(self.getcomment()) else: break
'Parse all addresses. Returns a list containing all of the addresses.'
def getaddrlist(self):
result = [] while (self.pos < len(self.field)): ad = self.getaddress() if ad: result += ad else: result.append(('', '')) return result
'Parse the next address.'
def getaddress(self):
self.commentlist = [] self.gotonext() oldpos = self.pos oldcl = self.commentlist plist = self.getphraselist() self.gotonext() returnlist = [] if (self.pos >= len(self.field)): if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif (self.field[self.pos] in '.@'): self.pos = oldpos self.commentlist = oldcl addrspec = self.getaddrspec() returnlist = [(SPACE.join(self.commentlist), addrspec)] elif (self.field[self.pos] == ':'): returnlist = [] fieldlen = len(self.field) self.pos += 1 while (self.pos < len(self.field)): self.gotonext() if ((self.pos < fieldlen) and (self.field[self.pos] == ';')): self.pos += 1 break returnlist = (returnlist + self.getaddress()) elif (self.field[self.pos] == '<'): routeaddr = self.getrouteaddr() if self.commentlist: returnlist = [((((SPACE.join(plist) + ' (') + ' '.join(self.commentlist)) + ')'), routeaddr)] else: returnlist = [(SPACE.join(plist), routeaddr)] elif plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif (self.field[self.pos] in self.specials): self.pos += 1 self.gotonext() if ((self.pos < len(self.field)) and (self.field[self.pos] == ',')): self.pos += 1 return returnlist
'Parse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec.'
def getrouteaddr(self):
if (self.field[self.pos] != '<'): return expectroute = False self.pos += 1 self.gotonext() adlist = '' while (self.pos < len(self.field)): if expectroute: self.getdomain() expectroute = False elif (self.field[self.pos] == '>'): self.pos += 1 break elif (self.field[self.pos] == '@'): self.pos += 1 expectroute = True elif (self.field[self.pos] == ':'): self.pos += 1 else: adlist = self.getaddrspec() self.pos += 1 break self.gotonext() return adlist
'Parse an RFC 2822 addr-spec.'
def getaddrspec(self):
aslist = [] self.gotonext() while (self.pos < len(self.field)): if (self.field[self.pos] == '.'): aslist.append('.') self.pos += 1 elif (self.field[self.pos] == '"'): aslist.append(('"%s"' % quote(self.getquote()))) elif (self.field[self.pos] in self.atomends): break else: aslist.append(self.getatom()) self.gotonext() if ((self.pos >= len(self.field)) or (self.field[self.pos] != '@')): return EMPTYSTRING.join(aslist) aslist.append('@') self.pos += 1 self.gotonext() return (EMPTYSTRING.join(aslist) + self.getdomain())
'Get the complete domain name from an address.'
def getdomain(self):
sdlist = [] while (self.pos < len(self.field)): if (self.field[self.pos] in self.LWS): self.pos += 1 elif (self.field[self.pos] == '('): self.commentlist.append(self.getcomment()) elif (self.field[self.pos] == '['): sdlist.append(self.getdomainliteral()) elif (self.field[self.pos] == '.'): self.pos += 1 sdlist.append('.') elif (self.field[self.pos] in self.atomends): break else: sdlist.append(self.getatom()) return EMPTYSTRING.join(sdlist)
'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 2822 comments are allowed within the parsed fragment.'
def getdelimited(self, beginchar, endchars, allowcomments=True):
if (self.field[self.pos] != beginchar): return '' slist = [''] quote = False self.pos += 1 while (self.pos < len(self.field)): if quote: slist.append(self.field[self.pos]) quote = False elif (self.field[self.pos] in endchars): self.pos += 1 break elif (allowcomments and (self.field[self.pos] == '(')): slist.append(self.getcomment()) continue elif (self.field[self.pos] == '\\'): quote = True else: slist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(slist)
'Get a quote-delimited fragment from self\'s field.'
def getquote(self):
return self.getdelimited('"', '"\r', False)
'Get a parenthesis-delimited fragment from self\'s field.'
def getcomment(self):
return self.getdelimited('(', ')\r', True)
'Parse an RFC 2822 domain-literal.'
def getdomainliteral(self):
return ('[%s]' % self.getdelimited('[', ']\r', False))
'Parse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.\' (which is legal in phrases).'
def getatom(self, atomends=None):
atomlist = [''] if (atomends is None): atomends = self.atomends while (self.pos < len(self.field)): if (self.field[self.pos] in atomends): break else: atomlist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(atomlist)
'Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space.'
def getphraselist(self):
plist = [] while (self.pos < len(self.field)): if (self.field[self.pos] in self.FWS): self.pos += 1 elif (self.field[self.pos] == '"'): plist.append(self.getquote()) elif (self.field[self.pos] == '('): self.commentlist.append(self.getcomment()) elif (self.field[self.pos] in self.phraseends): break else: plist.append(self.getatom(self.phraseends)) return plist
'Return the content-transfer-encoding used for body encoding. This is either the string `quoted-printable\' or `base64\' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate. Returns "quoted-printable" if self.body_encoding is QP. Returns "base64" if self.body_encoding is BASE64. Returns "7bit" otherwise.'
def get_body_encoding(self):
assert (self.body_encoding != SHORTEST) if (self.body_encoding == QP): return 'quoted-printable' elif (self.body_encoding == BASE64): return 'base64' else: return encode_7or8bit
'Convert a string from the input_codec to the output_codec.'
def convert(self, s):
if (self.input_codec != self.output_codec): return unicode(s, self.input_codec).encode(self.output_codec) else: return s
'Convert a possibly multibyte string to a safely splittable format. Uses the input_codec to try and convert the string to Unicode, so it can be safely split on character boundaries (even for multibyte characters). Returns the string as-is if it isn\'t known how to convert it to Unicode with the input_charset. Characters that could not be converted to Unicode will be replaced with the Unicode replacement character U+FFFD.'
def to_splittable(self, s):
if (isinstance(s, unicode) or (self.input_codec is None)): return s try: return unicode(s, self.input_codec, 'replace') except LookupError: return s
'Convert a splittable string back into an encoded string. Uses the proper codec to try and convert the string from Unicode back into an encoded format. Return the string as-is if it is not Unicode, or if it could not be converted from Unicode. Characters that could not be converted from Unicode will be replaced with an appropriate character (usually \'?\'). If to_output is True (the default), uses output_codec to convert to an encoded format. If to_output is False, uses input_codec.'
def from_splittable(self, ustr, to_output=True):
if to_output: codec = self.output_codec else: codec = self.input_codec if ((not isinstance(ustr, unicode)) or (codec is None)): return ustr try: return ustr.encode(codec, 'replace') except LookupError: return ustr
'Return the output character set. This is self.output_charset if that is not None, otherwise it is self.input_charset.'
def get_output_charset(self):
return (self.output_charset or self.input_charset)
'Return the length of the encoded header string.'
def encoded_header_len(self, s):
cset = self.get_output_charset() if (self.header_encoding == BASE64): return ((email.base64mime.base64_len(s) + len(cset)) + MISC_LEN) elif (self.header_encoding == QP): return ((email.quoprimime.header_quopri_len(s) + len(cset)) + MISC_LEN) elif (self.header_encoding == SHORTEST): lenb64 = email.base64mime.base64_len(s) lenqp = email.quoprimime.header_quopri_len(s) return ((min(lenb64, lenqp) + len(cset)) + MISC_LEN) else: return len(s)
'Header-encode a string, optionally converting it to output_charset. If convert is True, the string will be converted from the input charset to the output charset automatically. This is not useful for multibyte character sets, which have line length issues (multibyte characters must be split on a character, not a byte boundary); use the high-level Header class to deal with these issues. convert defaults to False. The type of encoding (base64 or quoted-printable) will be based on self.header_encoding.'
def header_encode(self, s, convert=False):
cset = self.get_output_charset() if convert: s = self.convert(s) if (self.header_encoding == BASE64): return email.base64mime.header_encode(s, cset) elif (self.header_encoding == QP): return email.quoprimime.header_encode(s, cset, maxlinelen=None) elif (self.header_encoding == SHORTEST): lenb64 = email.base64mime.base64_len(s) lenqp = email.quoprimime.header_quopri_len(s) if (lenb64 < lenqp): return email.base64mime.header_encode(s, cset) else: return email.quoprimime.header_encode(s, cset, maxlinelen=None) else: return s
'Body-encode a string and convert it to output_charset. If convert is True (the default), the string will be converted from the input charset to output charset automatically. Unlike header_encode(), there are no issues with byte boundaries and multibyte charsets in email bodies, so this is usually pretty safe. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding.'
def body_encode(self, s, convert=True):
if convert: s = self.convert(s) if (self.body_encoding is BASE64): return email.base64mime.body_encode(s) elif (self.body_encoding is QP): return email.quoprimime.body_encode(s) else: return s
'Create a MIME-compliant header that can contain many character sets. Optional s is the initial header value. If None, the initial header value is not set. You can later append to the header with .append() method calls. s may be a byte string or a Unicode string, but see the .append() documentation for semantics. Optional charset serves two purposes: it has the same meaning as the charset argument to the .append() method. It also sets the default character set for all subsequent .append() calls that omit the charset argument. If charset is not provided in the constructor, the us-ascii charset is used both as s\'s initial charset and as the default for subsequent .append() calls. The maximum line length can be specified explicit via maxlinelen. For splitting the first line to a shorter value (to account for the field header which isn\'t included in s, e.g. `Subject\') pass in the name of the field in header_name. The default maxlinelen is 76. continuation_ws must be RFC 2822 compliant folding whitespace (usually either a space or a hard tab) which will be prepended to continuation lines. errors is passed through to the .append() call.'
def __init__(self, s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict'):
if (charset is None): charset = USASCII if (not isinstance(charset, Charset)): charset = Charset(charset) self._charset = charset self._continuation_ws = continuation_ws cws_expanded_len = len(continuation_ws.replace(' DCTB ', SPACE8)) self._chunks = [] if (s is not None): self.append(s, charset, errors) if (maxlinelen is None): maxlinelen = MAXLINELEN if (header_name is None): self._firstlinelen = maxlinelen else: self._firstlinelen = ((maxlinelen - len(header_name)) - 2) self._maxlinelen = (maxlinelen - cws_expanded_len)
'A synonym for self.encode().'
def __str__(self):
return self.encode()
'Helper for the built-in unicode function.'
def __unicode__(self):
uchunks = [] lastcs = None for (s, charset) in self._chunks: nextcs = charset if uchunks: if (lastcs not in (None, 'us-ascii')): if (nextcs in (None, 'us-ascii')): uchunks.append(USPACE) nextcs = None elif (nextcs not in (None, 'us-ascii')): uchunks.append(USPACE) lastcs = nextcs uchunks.append(unicode(s, str(charset))) return UEMPTYSTRING.join(uchunks)
'Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is true), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In this case, when producing an RFC 2822 compliant header using RFC 2047 rules, the Unicode string will be encoded using the following charsets in order: us-ascii, the charset hint, utf-8. The first character set not to provoke a UnicodeError is used. Optional `errors\' is passed as the third argument to any unicode() or ustr.encode() call.'
def append(self, s, charset=None, errors='strict'):
if (charset is None): charset = self._charset elif (not isinstance(charset, Charset)): charset = Charset(charset) if (charset != '8bit'): if isinstance(s, str): incodec = (charset.input_codec or 'us-ascii') ustr = unicode(s, incodec, errors) outcodec = (charset.output_codec or 'us-ascii') ustr.encode(outcodec, errors) elif isinstance(s, unicode): for charset in (USASCII, charset, UTF8): try: outcodec = (charset.output_codec or 'us-ascii') s = s.encode(outcodec, errors) break except UnicodeError: pass else: assert False, 'utf-8 conversion failed' self._chunks.append((s, charset))
'Encode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. This method will do its best to convert the string to the correct character set used in email, and encode and line wrap it safely with the appropriate scheme for that character set. If the given charset is not known or an error occurs during conversion, this function will return the header untouched. Optional splitchars is a string containing characters to split long ASCII lines on, in rough support of RFC 2822\'s `highest level syntactic breaks\'. This doesn\'t affect RFC 2047 encoded lines.'
def encode(self, splitchars=';, '):
newchunks = [] maxlinelen = self._firstlinelen lastlen = 0 for (s, charset) in self._chunks: targetlen = ((maxlinelen - lastlen) - 1) if (targetlen < charset.encoded_header_len('')): targetlen = maxlinelen newchunks += self._split(s, charset, targetlen, splitchars) (lastchunk, lastcharset) = newchunks[(-1)] lastlen = lastcharset.encoded_header_len(lastchunk) value = self._encode_chunks(newchunks, maxlinelen) if _embeded_header.search(value): raise HeaderParseError('header value appears to contain an embedded header: {!r}'.format(value)) return value
'This constructor adds a Content-Type: and a MIME-Version: header. The Content-Type: header is taken from the _maintype and _subtype arguments. Additional parameters for this header are taken from the keyword arguments.'
def __init__(self, _maintype, _subtype, **_params):
message.Message.__init__(self) ctype = ('%s/%s' % (_maintype, _subtype)) self.add_header('Content-Type', ctype, **_params) self['MIME-Version'] = '1.0'
'Create a text/* type MIME document. _text is the string for this message object. _subtype is the MIME sub content type, defaulting to "plain". _charset is the character set parameter added to the Content-Type header. This defaults to "us-ascii". Note that as a side-effect, the Content-Transfer-Encoding header will also be set.'
def __init__(self, _text, _subtype='plain', _charset='us-ascii'):
MIMENonMultipart.__init__(self, 'text', _subtype, **{'charset': _charset}) self.set_payload(_text, _charset)
'Create an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to \'octet-stream\'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header.'
def __init__(self, _data, _subtype='octet-stream', _encoder=encoders.encode_base64, **_params):
if (_subtype is None): raise TypeError('Invalid application MIME subtype') MIMENonMultipart.__init__(self, 'application', _subtype, **_params) self.set_payload(_data) _encoder(self)
'Create a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822).'
def __init__(self, _msg, _subtype='rfc822'):
MIMENonMultipart.__init__(self, 'message', _subtype) if (not isinstance(_msg, message.Message)): raise TypeError('Argument is not an instance of Message') message.Message.attach(self, _msg) self.set_default_type('message/rfc822')
'Create an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python `imghdr\' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header.'
def __init__(self, _imagedata, _subtype=None, _encoder=encoders.encode_base64, **_params):
if (_subtype is None): _subtype = imghdr.what(None, _imagedata) if (_subtype is None): raise TypeError('Could not guess image MIME subtype') MIMENonMultipart.__init__(self, 'image', _subtype, **_params) self.set_payload(_imagedata) _encoder(self)
'Creates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed\'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method. Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument).'
def __init__(self, _subtype='mixed', boundary=None, _subparts=None, **_params):
MIMEBase.__init__(self, 'multipart', _subtype, **_params) self._payload = [] if _subparts: for p in _subparts: self.attach(p) if boundary: self.set_boundary(boundary)
'Create an audio/* type MIME document. _audiodata is a string containing the raw audio data. If this data can be decoded by the standard Python `sndhdr\' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific audio subtype via the _subtype parameter. If _subtype is not given, and no subtype can be guessed, a TypeError is raised. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header.'
def __init__(self, _audiodata, _subtype=None, _encoder=encoders.encode_base64, **_params):
if (_subtype is None): _subtype = _whatsnd(_audiodata) if (_subtype is None): raise TypeError('Could not find audio MIME subtype') MIMENonMultipart.__init__(self, 'audio', _subtype, **_params) self.set_payload(_audiodata) _encoder(self)
'Like assertEqual except use ndiff for readable output.'
def ndiffAssertEqual(self, first, second):
if (first != second): sfirst = str(first) ssecond = str(second) diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) fp = StringIO() print >>fp, NL, NL.join(diff) raise self.failureException, fp.getvalue()
'Test for parsing a date with a two-digit year. Parsing a date with a two-digit year should return the correct four-digit year. RFC822 allows two-digit years, but RFC2822 (which obsoletes RFC822) requires four-digit years.'
def test_parsedate_y2k(self):
self.assertEqual(Utils.parsedate_tz('25 Feb 03 13:47:26 -0800'), Utils.parsedate_tz('25 Feb 2003 13:47:26 -0800')) self.assertEqual(Utils.parsedate_tz('25 Feb 71 13:47:26 -0800'), Utils.parsedate_tz('25 Feb 1971 13:47:26 -0800'))
'Test proper handling of a nested comment'
def test_getaddresses_embedded_comment(self):
eq = self.assertEqual addrs = Utils.getaddresses(['User ((nested comment)) <[email protected]>']) eq(addrs[0][1], '[email protected]')
'FeedParser BufferedSubFile.push() assumed it received complete line endings. A CR ending one push() followed by a LF starting the next push() added an empty line.'
def test_pushCR_LF(self):
imt = [('a\r \n', 2), ('b', 0), ('c\n', 1), ('', 0), ('d\r\n', 1), ('e\r', 0), ('\nf', 1), ('\r\n', 1)] from email.feedparser import BufferedSubFile, NeedMoreData bsf = BufferedSubFile() om = [] nt = 0 for (il, n) in imt: bsf.push(il) nt += n n1 = 0 for ol in iter(bsf.readline, NeedMoreData): om.append(ol) n1 += 1 self.assertEqual(n, n1) self.assertEqual(len(om), nt) self.assertEqual(''.join([il for (il, n) in imt]), ''.join(om))
'Like assertEqual except use ndiff for readable output.'
def ndiffAssertEqual(self, first, second):
if (first != second): sfirst = str(first) ssecond = str(second) diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) fp = StringIO() print >>fp, NL, NL.join(diff) raise self.failureException, fp.getvalue()
'Test proper handling of a nested comment'
def test_getaddresses_embedded_comment(self):
eq = self.assertEqual addrs = utils.getaddresses(['User ((nested comment)) <[email protected]>']) eq(addrs[0][1], '[email protected]')
'Return the entire formatted message as a string. This includes the headers, body, and envelope header.'
def __str__(self):
return self.as_string(unixfrom=True)
'Return the entire formatted message as a string. Optional `unixfrom\' when True, means include the Unix From_ envelope header. This is a convenience method and may not generate the message exactly as you intend because by default it mangles lines that begin with "From ". For more flexibility, use the flatten() method of a Generator instance.'
def as_string(self, unixfrom=False):
from email.generator import Generator fp = StringIO() g = Generator(fp) g.flatten(self, unixfrom=unixfrom) return fp.getvalue()
'Return True if the message consists of multiple parts.'
def is_multipart(self):
return isinstance(self._payload, list)
'Add the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead.'
def attach(self, payload):
if (self._payload is None): self._payload = [payload] else: self._payload.append(payload)
'Return a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message\'s payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header\'s value is `quoted-printable\' or `base64\'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned.'
def get_payload(self, i=None, decode=False):
if (i is None): payload = self._payload elif (not isinstance(self._payload, list)): raise TypeError(('Expected list, got %s' % type(self._payload))) else: payload = self._payload[i] if decode: if self.is_multipart(): return None cte = self.get('content-transfer-encoding', '').lower() if (cte == 'quoted-printable'): return utils._qdecode(payload) elif (cte == 'base64'): try: return utils._bdecode(payload) except binascii.Error: return payload elif (cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue')): sfp = StringIO() try: uu.decode(StringIO((payload + '\n')), sfp, quiet=True) payload = sfp.getvalue() except uu.Error: return payload return payload
'Set the payload to the given value. Optional charset sets the message\'s default character set. See set_charset() for details.'
def set_payload(self, payload, charset=None):
self._payload = payload if (charset is not None): self.set_charset(charset)
'Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed.'
def set_charset(self, charset):
if (charset is None): self.del_param('charset') self._charset = None return if isinstance(charset, basestring): charset = email.charset.Charset(charset) if (not isinstance(charset, email.charset.Charset)): raise TypeError(charset) self._charset = charset if ('MIME-Version' not in self): self.add_header('MIME-Version', '1.0') if ('Content-Type' not in self): self.add_header('Content-Type', 'text/plain', charset=charset.get_output_charset()) else: self.set_param('charset', charset.get_output_charset()) if isinstance(self._payload, unicode): self._payload = self._payload.encode(charset.output_charset) if (str(charset) != charset.get_output_charset()): self._payload = charset.body_encode(self._payload) if ('Content-Transfer-Encoding' not in self): cte = charset.get_body_encoding() try: cte(self) except TypeError: self._payload = charset.body_encode(self._payload) self.add_header('Content-Transfer-Encoding', cte)
'Return the Charset instance associated with the message\'s payload.'
def get_charset(self):
return self._charset
'Return the total number of headers, including duplicates.'
def __len__(self):
return len(self._headers)
'Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name.'
def __getitem__(self, name):
return self.get(name)
'Set the value of a header. Note: this does not overwrite an existing header with the same field name. Use __delitem__() first to delete any existing headers.'
def __setitem__(self, name, val):
self._headers.append((name, val))
'Delete all occurrences of a header, if present. Does not raise an exception if the header is missing.'
def __delitem__(self, name):
name = name.lower() newheaders = [] for (k, v) in self._headers: if (k.lower() != name): newheaders.append((k, v)) self._headers = newheaders
'Return true if the message contains the header.'
def has_key(self, name):
missing = object() return (self.get(name, missing) is not missing)
'Return a list of all the message\'s header field names. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def keys(self):
return [k for (k, v) in self._headers]
'Return a list of all the message\'s header values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def values(self):
return [v for (k, v) in self._headers]
'Get all the message\'s header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.'
def items(self):
return self._headers[:]
'Get a header value. Like __getitem__() but return failobj instead of None when the field is missing.'
def get(self, name, failobj=None):
name = name.lower() for (k, v) in self._headers: if (k.lower() == name): return v return failobj
'Return a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None).'
def get_all(self, name, failobj=None):
values = [] name = name.lower() for (k, v) in self._headers: if (k.lower() == name): values.append(v) if (not values): return failobj return values
'Extended header setting. name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. If a parameter value contains non-ASCII characters it must be specified as a three-tuple of (charset, language, value), in which case it will be encoded according to RFC2231 rules. Example: msg.add_header(\'content-disposition\', \'attachment\', filename=\'bud.gif\')'
def add_header(self, _name, _value, **_params):
parts = [] for (k, v) in _params.items(): if (v is None): parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) if (_value is not None): parts.insert(0, _value) self._headers.append((_name, SEMISPACE.join(parts)))
'Replace a header. Replace the first matching header found in the message, retaining header order and case. If no matching header was found, a KeyError is raised.'
def replace_header(self, _name, _value):
_name = _name.lower() for (i, (k, v)) in zip(range(len(self._headers)), self._headers): if (k.lower() == _name): self._headers[i] = (k, _value) break else: raise KeyError(_name)
'Return the message\'s content type. The returned string is coerced to lower case of the form `maintype/subtype\'. If there was no Content-Type header in the message, the default type as given by get_default_type() will be returned. Since according to RFC 2045, messages always have a default type this will always return a value. RFC 2045 defines a message\'s default type to be text/plain unless it appears inside a multipart/digest container, in which case it would be message/rfc822.'
def get_content_type(self):
missing = object() value = self.get('content-type', missing) if (value is missing): return self.get_default_type() ctype = _splitparam(value)[0].lower() if (ctype.count('/') != 1): return 'text/plain' return ctype
'Return the message\'s main content type. This is the `maintype\' part of the string returned by get_content_type().'
def get_content_maintype(self):
ctype = self.get_content_type() return ctype.split('/')[0]
'Returns the message\'s sub-content type. This is the `subtype\' part of the string returned by get_content_type().'
def get_content_subtype(self):
ctype = self.get_content_type() return ctype.split('/')[1]
'Return the `default\' content type. Most messages have a default content type of text/plain, except for messages that are subparts of multipart/digest containers. Such subparts have a default content type of message/rfc822.'
def get_default_type(self):
return self._default_type
'Set the `default\' content type. ctype should be either "text/plain" or "message/rfc822", although this is not enforced. The default content type is not stored in the Content-Type header.'
def set_default_type(self, ctype):
self._default_type = ctype
'Return the message\'s Content-Type parameters, as a list. The elements of the returned list are 2-tuples of key/value pairs, as split on the `=\' sign. The left hand side of the `=\' is the key, while the right hand side is the value. If there is no `=\' sign in the parameter the value is the empty string. The value is as described in the get_param() method. Optional failobj is the object to return if there is no Content-Type header. Optional header is the header to search instead of Content-Type. If unquote is True, the value is unquoted.'
def get_params(self, failobj=None, header='content-type', unquote=True):
missing = object() params = self._get_params_preserve(missing, header) if (params is missing): return failobj if unquote: return [(k, _unquotevalue(v)) for (k, v) in params] else: return params
'Return the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional header is the header to search instead of Content-Type. Parameter keys are always compared case insensitively. The return value can either be a string, or a 3-tuple if the parameter was RFC 2231 encoded. When it\'s a 3-tuple, the elements of the value are of the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and LANGUAGE can be None, in which case you should consider VALUE to be encoded in the us-ascii charset. You can usually ignore LANGUAGE. Your application should be prepared to deal with 3-tuple return values, and can convert the parameter to a Unicode string like so: param = msg.get_param(\'foo\') if isinstance(param, tuple): param = unicode(param[2], param[0] or \'us-ascii\') In any case, the parameter value (either the returned string, or the VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False.'
def get_param(self, param, failobj=None, header='content-type', unquote=True):
if (header not in self): return failobj for (k, v) in self._get_params_preserve(failobj, header): if (k.lower() == param.lower()): if unquote: return _unquotevalue(v) else: return v return failobj
'Set a parameter in the Content-Type header. If the parameter already exists in the header, its value will be replaced with the new value. If header is Content-Type and has not yet been defined for this message, it will be set to "text/plain" and the new parameter and value will be appended as per RFC 2045. An alternate header can be specified in the header argument, and all parameters will be quoted as necessary unless requote is False. If charset is specified, the parameter will be encoded according to RFC 2231. Optional language specifies the RFC 2231 language, defaulting to the empty string. Both charset and language should be strings.'
def set_param(self, param, value, header='Content-Type', requote=True, charset=None, language=''):
if ((not isinstance(value, tuple)) and charset): value = (charset, language, value) if ((header not in self) and (header.lower() == 'content-type')): ctype = 'text/plain' else: ctype = self.get(header) if (not self.get_param(param, header=header)): if (not ctype): ctype = _formatparam(param, value, requote) else: ctype = SEMISPACE.join([ctype, _formatparam(param, value, requote)]) else: ctype = '' for (old_param, old_value) in self.get_params(header=header, unquote=requote): append_param = '' if (old_param.lower() == param.lower()): append_param = _formatparam(param, value, requote) else: append_param = _formatparam(old_param, old_value, requote) if (not ctype): ctype = append_param else: ctype = SEMISPACE.join([ctype, append_param]) if (ctype != self.get(header)): del self[header] self[header] = ctype
'Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header.'
def del_param(self, param, header='content-type', requote=True):
if (header not in self): return new_ctype = '' for (p, v) in self.get_params(header=header, unquote=requote): if (p.lower() != param.lower()): if (not new_ctype): new_ctype = _formatparam(p, v, requote) else: new_ctype = SEMISPACE.join([new_ctype, _formatparam(p, v, requote)]) if (new_ctype != self.get(header)): del self[header] self[header] = new_ctype
'Set the main type and subtype for the Content-Type header. type must be a string in the form "maintype/subtype", otherwise a ValueError is raised. This method replaces the Content-Type header, keeping all the parameters in place. If requote is False, this leaves the existing header\'s quoting as is. Otherwise, the parameters will be quoted (the default). An alternative header can be specified in the header argument. When the Content-Type header is set, we\'ll always also add a MIME-Version header.'
def set_type(self, type, header='Content-Type', requote=True):
if (not (type.count('/') == 1)): raise ValueError if (header.lower() == 'content-type'): del self['mime-version'] self['MIME-Version'] = '1.0' if (header not in self): self[header] = type return params = self.get_params(header=header, unquote=requote) del self[header] self[header] = type for (p, v) in params[1:]: self.set_param(p, v, header, requote)
'Return the filename associated with the payload if present. The filename is extracted from the Content-Disposition header\'s `filename\' parameter, and it is unquoted. If that header is missing the `filename\' parameter, this method falls back to looking for the `name\' parameter.'
def get_filename(self, failobj=None):
missing = object() filename = self.get_param('filename', missing, 'content-disposition') if (filename is missing): filename = self.get_param('name', missing, 'content-type') if (filename is missing): return failobj return utils.collapse_rfc2231_value(filename).strip()
'Return the boundary associated with the payload if present. The boundary is extracted from the Content-Type header\'s `boundary\' parameter, and it is unquoted.'
def get_boundary(self, failobj=None):
missing = object() boundary = self.get_param('boundary', missing) if (boundary is missing): return failobj return utils.collapse_rfc2231_value(boundary).rstrip()
'Set the boundary parameter in Content-Type to \'boundary\'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header.'
def set_boundary(self, boundary):
missing = object() params = self._get_params_preserve(missing, 'content-type') if (params is missing): raise errors.HeaderParseError('No Content-Type header found') newparams = [] foundp = False for (pk, pv) in params: if (pk.lower() == 'boundary'): newparams.append(('boundary', ('"%s"' % boundary))) foundp = True else: newparams.append((pk, pv)) if (not foundp): newparams.append(('boundary', ('"%s"' % boundary))) newheaders = [] for (h, v) in self._headers: if (h.lower() == 'content-type'): parts = [] for (k, v) in newparams: if (v == ''): parts.append(k) else: parts.append(('%s=%s' % (k, v))) newheaders.append((h, SEMISPACE.join(parts))) else: newheaders.append((h, v)) self._headers = newheaders
'Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned.'
def get_content_charset(self, failobj=None):
missing = object() charset = self.get_param('charset', missing) if (charset is missing): return failobj if isinstance(charset, tuple): pcharset = (charset[0] or 'us-ascii') try: charset = unicode(charset[2], pcharset).encode('us-ascii') except (LookupError, UnicodeError): charset = charset[2] try: if isinstance(charset, str): charset = unicode(charset, 'us-ascii') charset = charset.encode('us-ascii') except UnicodeError: return failobj return charset.lower()
'Return a list containing the charset(s) used in this message. The returned list of items describes the Content-Type headers\' charset parameter for this message and all the subparts in its payload. Each item will either be a string (the value of the charset parameter in the Content-Type header of that part) or the value of the \'failobj\' parameter (defaults to None), if the part does not have a main MIME type of "text", or the charset is not defined. The list will contain one string for each part of the message, plus one for the container message (i.e. self), so that a non-multipart message will still return a list of length 1.'
def get_charsets(self, failobj=None):
return [part.get_content_charset(failobj) for part in self.walk()]
'Return first release in which this feature was recognized. This is a 5-tuple, of the same form as sys.version_info.'
def getOptionalRelease(self):
return self.optional
'Return release in which this feature will become mandatory. This is a 5-tuple, of the same form as sys.version_info, or, if the feature was dropped, is None.'
def getMandatoryRelease(self):
return self.mandatory
'Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically.'
def mtime(self):
return self.last_checked
'Sets the time the robots.txt file was last fetched to the current time.'
def modified(self):
import time self.last_checked = time.time()
'Sets the URL referring to a robots.txt file.'
def set_url(self, url):
self.url = url (self.host, self.path) = urlparse.urlparse(url)[1:3]
'Reads the robots.txt URL and feeds it to the parser.'
def read(self):
opener = URLopener() f = opener.open(self.url) lines = [line.strip() for line in f] f.close() self.errcode = opener.errcode if (self.errcode in (401, 403)): self.disallow_all = True elif ((self.errcode >= 400) and (self.errcode < 500)): self.allow_all = True elif ((self.errcode == 200) and lines): self.parse(lines)
'parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.'
def parse(self, lines):
state = 0 linenumber = 0 entry = Entry() self.modified() for line in lines: linenumber += 1 if (not line): if (state == 1): entry = Entry() state = 0 elif (state == 2): self._add_entry(entry) entry = Entry() state = 0 i = line.find('#') if (i >= 0): line = line[:i] line = line.strip() if (not line): continue line = line.split(':', 1) if (len(line) == 2): line[0] = line[0].strip().lower() line[1] = urllib.unquote(line[1].strip()) if (line[0] == 'user-agent'): if (state == 2): self._add_entry(entry) entry = Entry() entry.useragents.append(line[1]) state = 1 elif (line[0] == 'disallow'): if (state != 0): entry.rulelines.append(RuleLine(line[1], False)) state = 2 elif (line[0] == 'allow'): if (state != 0): entry.rulelines.append(RuleLine(line[1], True)) state = 2 if (state == 2): self._add_entry(entry)
'using the parsed robots.txt decide if useragent can fetch url'
def can_fetch(self, useragent, url):
if self.disallow_all: return False if self.allow_all: return True if (not self.last_checked): return False parsed_url = urlparse.urlparse(urllib.unquote(url)) url = urlparse.urlunparse(('', '', parsed_url.path, parsed_url.params, parsed_url.query, parsed_url.fragment)) url = urllib.quote(url) if (not url): url = '/' for entry in self.entries: if entry.applies_to(useragent): return entry.allowance(url) if self.default_entry: return self.default_entry.allowance(url) return True
'check if this entry applies to the specified agent'
def applies_to(self, useragent):
useragent = useragent.split('/')[0].lower() for agent in self.useragents: if (agent == '*'): return True agent = agent.lower() if (agent in useragent): return True return False
'Preconditions: - our agent applies to this entry - filename is URL decoded'
def allowance(self, filename):
for line in self.rulelines: if line.applies_to(filename): return line.allowance return True
'Specify whether to record warnings and if an alternative module should be used other than sys.modules[\'warnings\']. For compatibility with Python 3.0, please consider all arguments to be keyword-only.'
def __init__(self, record=False, module=None):
self._record = record self._module = (sys.modules['warnings'] if (module is None) else module) self._entered = False
'Create _ASN1Object from OpenSSL numeric ID'
@classmethod def fromnid(cls, nid):
return super(_ASN1Object, cls).__new__(cls, *_nid2obj(nid))
'Create _ASN1Object from short name, long name or OID'
@classmethod def fromname(cls, name):
return super(_ASN1Object, cls).__new__(cls, *_txt2obj(name, name=True))
'Read up to LEN bytes and return them. Return zero-length string on EOF.'
def read(self, len=1024, buffer=None):
self._checkClosed() if (not self._sslobj): raise ValueError('Read on closed or unwrapped SSL socket.') try: if (buffer is not None): v = self._sslobj.read(len, buffer) else: v = self._sslobj.read(len) return v except SSLError as x: if ((x.args[0] == SSL_ERROR_EOF) and self.suppress_ragged_eofs): if (buffer is not None): return 0 else: return '' else: raise
'Write DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted.'
def write(self, data):
self._checkClosed() if (not self._sslobj): raise ValueError('Write on closed or unwrapped SSL socket.') return self._sslobj.write(data)
'Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated.'
def getpeercert(self, binary_form=False):
self._checkClosed() self._check_connected() return self._sslobj.peer_certificate(binary_form)