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... | 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
|
'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):
| 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)].en... |
'_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.... |
'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):
| 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.
Character... | 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 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
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):
... |
'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)
elif (self.header_encoding == QP):
return email.quoprimime.header_encode(s, cset, maxlinelen=None)
elif (self.header_encoding =... |
'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)
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.
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)
|
'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)
|
'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)
|
'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 i... |
'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... | 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 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 None
cte = self.get... |
'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 Type... | 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 ('... |
'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)))
|
'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
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 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... |
'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, Un... |
'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 val... | 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.e... |
'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)
entr... |
'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))
ur... |
'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... |
'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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.