desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length \'self.width\' or less. (If \'break_long_words\' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo \'break...
def _wrap_chunks(self, chunks):
lines = [] if (self.width <= 0): raise ValueError(('invalid width %r (must be > 0)' % self.width)) chunks.reverse() while chunks: cur_line = [] cur_len = 0 if lines: indent = self.subsequent_indent else: indent = self.init...
'wrap(text : string) -> [string] Reformat the single paragraph in \'text\' so it fits in lines of no more than \'self.width\' columns, and return a list of wrapped lines. Tabs in \'text\' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space.'
def wrap(self, text):
text = self._munge_whitespace(text) chunks = self._split(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) return self._wrap_chunks(chunks)
'fill(text : string) -> string Reformat the single paragraph in \'text\' to fit in lines of no more than \'self.width\' columns, and return a new string containing the entire wrapped paragraph.'
def fill(self, text):
return '\n'.join(self.wrap(text))
'Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.'
def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
escape = (escape or self.escape) results = [] here = 0 pattern = re.compile('\\b((http|ftp)://\\S+[\\w/]|RFC[- ]?(\\d+)|PEP[- ]?(\\d+)|(self\\.)?((?:\\w|\\.)+))\\b') while 1: match = pattern.search(text, here) if (not match): break (start, end) = match.span(...
'Produce HTML documentation for a function or method object.'
def docroutine(self, object, name, mod=None, funcs={}, classes={}, methods={}, cl=None):
anchor = ((((cl and cl.__name__) or '') + '-') + name) note = '' title = ('<a name="%s"><strong>%s</strong></a>' % (self.escape(anchor), self.escape(name))) if inspect.ismethod(object): (args, varargs, varkw, defaults) = inspect.getargspec(object.im_func) argspec = inspect.formatargsp...
'Produce HTML documentation for an XML-RPC server.'
def docserver(self, server_name, package_documentation, methods):
fdict = {} for (key, value) in methods.items(): fdict[key] = ('#-' + key) fdict[value] = fdict[key] server_name = self.escape(server_name) head = ('<big><big><strong>%s</strong></big></big>' % server_name) result = self.heading(head, '#ffffff', '#7799ee') doc = self.markup(packag...
'Set the HTML title of the generated server documentation'
def set_server_title(self, server_title):
self.server_title = server_title
'Set the name of the generated HTML server documentation'
def set_server_name(self, server_name):
self.server_name = server_name
'Set the documentation string for the entire server.'
def set_server_documentation(self, server_documentation):
self.server_documentation = server_documentation
'generate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can choose to implement the _get_method_argstring(method_name) method to provide ...
def generate_html_documentation(self):
methods = {} for method_name in self.system_listMethods(): if (method_name in self.funcs): method = self.funcs[method_name] elif (self.instance is not None): method_info = [None, None] if hasattr(self.instance, '_get_method_argstring'): method_...
'Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation.'
def do_GET(self):
if (not self.is_rpc_path_valid()): self.report_404() return response = self.server.generate_html_documentation() self.send_response(200) self.send_header('Content-type', 'text/html') self.send_header('Content-length', str(len(response))) self.end_headers() self.wfile.write(re...
'Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation.'
def handle_get(self):
response = self.generate_html_documentation() print 'Content-Type: text/html' print ('Content-Length: %d' % len(response)) print sys.stdout.write(response)
'Read at least wtd bytes (or until EOF)'
def read(self, totalwtd):
decdata = '' wtd = totalwtd while (wtd > 0): if self.eof: return decdata wtd = (((wtd + 2) // 3) * 4) data = self.ifp.read(wtd) while 1: try: (decdatacur, self.eof) = binascii.a2b_hqx(data) break except binas...
'Initialize and reset this instance.'
def __init__(self, verbose=0):
self.verbose = verbose self.reset()
'Reset this instance. Loses all unprocessed data.'
def reset(self):
self.__starttag_text = None self.rawdata = '' self.stack = [] self.lasttag = '???' self.nomoretags = 0 self.literal = 0 markupbase.ParserBase.reset(self) return
'Enter literal mode (CDATA) till EOF. Intended for derived classes only.'
def setnomoretags(self):
self.nomoretags = self.literal = 1
'Enter literal mode (CDATA). Intended for derived classes only.'
def setliteral(self, *args):
self.literal = 1
'Feed some data to the parser. Call this as often as you want, with as little or as much text as you want (may include \' \'). (This just saves the text, all the processing is done by goahead().)'
def feed(self, data):
self.rawdata = (self.rawdata + data) self.goahead(0)
'Handle the remaining data.'
def close(self):
self.goahead(1)
'Convert character reference, may be overridden.'
def convert_charref(self, name):
try: n = int(name) except ValueError: return if (not (0 <= n <= 127)): return return self.convert_codepoint(n)
'Handle character reference, no need to override.'
def handle_charref(self, name):
replacement = self.convert_charref(name) if (replacement is None): self.unknown_charref(name) else: self.handle_data(replacement) return
'Convert entity references. As an alternative to overriding this method; one can tailor the results by setting up the self.entitydefs mapping appropriately.'
def convert_entityref(self, name):
table = self.entitydefs if (name in table): return table[name] else: return
'Handle entity references, no need to override.'
def handle_entityref(self, name):
replacement = self.convert_entityref(name) if (replacement is None): self.unknown_entityref(name) else: self.handle_data(replacement) return
'Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default), escapes From_ lines in the body of the message by putting a `>\' in front of them. Optional maxheaderlen specifies...
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
self._fp = outfp self._mangle_from_ = mangle_from_ self._maxheaderlen = maxheaderlen
'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...
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...
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 return
'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, optio...
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'") ...
'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):
(data, self._partial) = ((self._partial + data), '') parts = NLCRE_crack.split(data) self._partial = parts.pop() if ((not self._partial) and parts and parts[(-1)].endswith('\r')): self._partial = (parts.pop((-2)) + parts.pop()) lines = [] for i in range((len(parts) // 2)): lines....
'_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 return
'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() 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....
'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...
'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 se...
'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(...
'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 encounter...
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...
'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()) ...
'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-Tran...
def get_body_encoding(self):
if (self.body_encoding == QP): return 'quoted-printable' else: if (self.body_encoding == BASE64): return 'base64' 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. Character...
def to_splittable(self, s):
if (isinstance(s, unicode) or (self.input_codec is None)): return s else: try: return unicode(s, self.input_codec, 'replace') except LookupError: return s return
'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 a...
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 else: try: return ustr.encode(codec, 'replace') except LookupError: return ustr return
'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) else: if (self.header_encoding == QP): return ((email.quoprimime.header_quopri_len(s) + len(cset)) + MISC_LEN) if (self.header_encoding =...
'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...
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) else: if (self.header_encoding == QP): return email.quoprimime.header_encode(s, cset, maxlinelen=None) if (self...
'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 typ...
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) else: if (self.body_encoding is QP): return email.quoprimime.body_encode(s) 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. Op...
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): ...
'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 (nextc...
'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 by...
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) outcod...
'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 encod...
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) ...
'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 a...
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 additiona...
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) return
'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 "rfc82...
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....
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) return
'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...
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...
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) return
'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...
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
'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 Conte...
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 cte = self.get('con...
'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) return
'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 Type...
def set_charset(self, charset):
if (charset is None): self.del_param('charset') self._charset = None return else: if isinstance(charset, basestring): charset = email.charset.Charset(charset) if (not isinstance(charset, email.charset.Charset)): raise TypeError(charset) sel...
'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 co...
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))) r...
'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 ret...
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 valu...
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 else: if unquote: return [(k, _unquotevalue(v)) for (k, v) in params] 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 re...
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 alternat...
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): ...
'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(...
'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 p...
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...
'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 mes...
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...