"""Policy framework for the email package.Allows fine grained feature control of how the package parses and emits data."""import abcfrom email import headerfrom email import charset as _charsetfrom email.utils import _has_surrogates__all__ = ['Policy','Compat32','compat32',]class _PolicyBase:"""Policy Object basic framework.This class is useless unless subclassed. A subclass should defineclass attributes with defaults for any values that are to bemanaged by the Policy object. The constructor will then allownon-default values to be set for these attributes at instancecreation time. The instance will be callable, taking these sameattributes keyword arguments, and returning a new instanceidentical to the called instance except for those values changedby the keyword arguments. Instances may be added, yielding newinstances with any non-default values from the right handoperand overriding those in the left hand operand. That is,A + B == A(<non-default values of B>)The repr of an instance can be used to reconstruct the objectif and only if the repr of the values can be used to reconstructthose values."""def __init__(self, **kw):"""Create new Policy, possibly overriding some defaults.See class docstring for a list of overridable attributes."""for name, value in kw.items():if hasattr(self, name):super(_PolicyBase,self).__setattr__(name, value)else:raise TypeError("{!r} is an invalid keyword argument for {}".format(name, self.__class__.__name__))def __repr__(self):args = [ "{}={!r}".format(name, value)for name, value in self.__dict__.items() ]return "{}({})".format(self.__class__.__name__, ', '.join(args))def clone(self, **kw):"""Return a new instance with specified attributes changed.The new instance has the same attribute values as the current object,except for the changes passed in as keyword arguments."""newpolicy = self.__class__.__new__(self.__class__)for attr, value in self.__dict__.items():object.__setattr__(newpolicy, attr, value)for attr, value in kw.items():if not hasattr(self, attr):raise TypeError("{!r} is an invalid keyword argument for {}".format(attr, self.__class__.__name__))object.__setattr__(newpolicy, attr, value)return newpolicydef __setattr__(self, name, value):if hasattr(self, name):msg = "{!r} object attribute {!r} is read-only"else:msg = "{!r} object has no attribute {!r}"raise AttributeError(msg.format(self.__class__.__name__, name))def __add__(self, other):"""Non-default values from right operand override those from left.The object returned is a new instance of the subclass."""return self.clone(**other.__dict__)def _append_doc(doc, added_doc):doc = doc.rsplit('\n', 1)[0]added_doc = added_doc.split('\n', 1)[1]return doc + '\n' + added_docdef _extend_docstrings(cls):if cls.__doc__ and cls.__doc__.startswith('+'):cls.__doc__ = _append_doc(cls.__bases__[0].__doc__, cls.__doc__)for name, attr in cls.__dict__.items():if attr.__doc__ and attr.__doc__.startswith('+'):for c in (c for base in cls.__bases__ for c in base.mro()):doc = getattr(getattr(c, name), '__doc__')if doc:attr.__doc__ = _append_doc(doc, attr.__doc__)breakreturn clsclass Policy(_PolicyBase, metaclass=abc.ABCMeta):r"""Controls for how messages are interpreted and formatted.Most of the classes and many of the methods in the email package acceptPolicy objects as parameters. A Policy object contains a set of values andfunctions that control how input is interpreted and how output is rendered.For example, the parameter 'raise_on_defect' controls whether or not an RFCviolation results in an error being raised or not, while 'max_line_length'controls the maximum length of output lines when a Message is serialized.Any valid attribute may be overridden when a Policy is created by passingit as a keyword argument to the constructor. Policy objects are immutable,but a new Policy object can be created with only certain values changed bycalling the Policy instance with keyword arguments. Policy objects canalso be added, producing a new Policy object in which the non-defaultattributes set in the right hand operand overwrite those specified in theleft operand.Settable attributes:raise_on_defect -- If true, then defects should be raised as errors.Default: False.linesep -- string containing the value to use as separationbetween output lines. Default '\n'.cte_type -- Type of allowed content transfer encodings7bit -- ASCII only8bit -- Content-Transfer-Encoding: 8bit is allowedDefault: 8bit. Also controls the disposition of(RFC invalid) binary data in headers; see thedocumentation of the binary_fold method.max_line_length -- maximum length of lines, excluding 'linesep',during serialization. None or 0 means no linewrapping is done. Default is 78.mangle_from_ -- a flag that, when True escapes From_ lines in thebody of the message by putting a `>' in front ofthem. This is used when the message is beingserialized by a generator. Default: True.message_factory -- the class to use to create new message objects.If the value is None, the default is Message."""raise_on_defect = Falselinesep = '\n'cte_type = '8bit'max_line_length = 78mangle_from_ = Falsemessage_factory = Nonedef handle_defect(self, obj, defect):"""Based on policy, either raise defect or call register_defect.handle_defect(obj, defect)defect should be a Defect subclass, but in any case must be anException subclass. obj is the object on which the defect should beregistered if it is not raised. If the raise_on_defect is True, thedefect is raised as an error, otherwise the object and the defect arepassed to register_defect.This method is intended to be called by parsers that discover defects.The email package parsers always call it with Defect instances."""if self.raise_on_defect:raise defectself.register_defect(obj, defect)def register_defect(self, obj, defect):"""Record 'defect' on 'obj'.Called by handle_defect if raise_on_defect is False. This method ispart of the Policy API so that Policy subclasses can implement customdefect handling. The default implementation calls the append method ofthe defects attribute of obj. The objects used by the email package bydefault that get passed to this method will always have a defectsattribute with an append method."""obj.defects.append(defect)def header_max_count(self, name):"""Return the maximum allowed number of headers named 'name'.Called when a header is added to a Message object. If the returnedvalue is not 0 or None, and there are already a number of headers withthe name 'name' equal to the value returned, a ValueError is raised.Because the default behavior of Message's __setitem__ is to append thevalue to the list of headers, it is easy to create duplicate headerswithout realizing it. This method allows certain headers to be limitedin the number of instances of that header that may be added to aMessage programmatically. (The limit is not observed by the parser,which will faithfully produce as many headers as exist in the messagebeing parsed.)The default implementation returns None for all header names."""return None@abc.abstractmethoddef header_source_parse(self, sourcelines):"""Given a list of linesep terminated strings constituting the lines ofa single header, return the (name, value) tuple that should be storedin the model. The input lines should retain their terminating linesepcharacters. The lines passed in by the email package may containsurrogateescaped binary data."""raise NotImplementedError@abc.abstractmethoddef header_store_parse(self, name, value):"""Given the header name and the value provided by the applicationprogram, return the (name, value) that should be stored in the model."""raise NotImplementedError@abc.abstractmethoddef header_fetch_parse(self, name, value):"""Given the header name and the value from the model, return the valueto be returned to the application program that is requesting thatheader. The value passed in by the email package may containsurrogateescaped binary data if the lines were parsed by a BytesParser.The returned value should not contain any surrogateescaped data."""raise NotImplementedError@abc.abstractmethoddef fold(self, name, value):"""Given the header name and the value from the model, return a stringcontaining linesep characters that implement the folding of the headeraccording to the policy controls. The value passed in by the emailpackage may contain surrogateescaped binary data if the lines wereparsed by a BytesParser. The returned value should not contain anysurrogateescaped data."""raise NotImplementedError@abc.abstractmethoddef fold_binary(self, name, value):"""Given the header name and the value from the model, return binarydata containing linesep characters that implement the folding of theheader according to the policy controls. The value passed in by theemail package may contain surrogateescaped binary data."""raise NotImplementedError@_extend_docstringsclass Compat32(Policy):"""+This particular policy is the backward compatibility Policy. Itreplicates the behavior of the email package version 5.1."""mangle_from_ = Truedef _sanitize_header(self, name, value):# If the header value contains surrogates, return a Header using# the unknown-8bit charset to encode the bytes as encoded words.if not isinstance(value, str):# Assume it is already a header objectreturn valueif _has_surrogates(value):return header.Header(value, charset=_charset.UNKNOWN8BIT,header_name=name)else:return valuedef header_source_parse(self, sourcelines):"""+The name is parsed as everything up to the ':' and returned unmodified.The value is determined by stripping leading whitespace off theremainder of the first line, joining all subsequent lines together, andstripping any trailing carriage return or linefeed characters."""name, value = sourcelines[0].split(':', 1)value = value.lstrip(' \t') + ''.join(sourcelines[1:])return (name, value.rstrip('\r\n'))def header_store_parse(self, name, value):"""+The name and value are returned unmodified."""return (name, value)def header_fetch_parse(self, name, value):"""+If the value contains binary data, it is converted into a Header objectusing the unknown-8bit charset. Otherwise it is returned unmodified."""return self._sanitize_header(name, value)def fold(self, name, value):"""+Headers are folded using the Header folding algorithm, which preservesexisting line breaks in the value, and wraps each resulting line to themax_line_length. Non-ASCII binary data are CTE encoded using theunknown-8bit charset."""return self._fold(name, value, sanitize=True)def fold_binary(self, name, value):"""+Headers are folded using the Header folding algorithm, which preservesexisting line breaks in the value, and wraps each resulting line to themax_line_length. If cte_type is 7bit, non-ascii binary data is CTEencoded using the unknown-8bit charset. Otherwise the original sourceheader is used, with its existing line breaks and/or binary data."""folded = self._fold(name, value, sanitize=self.cte_type=='7bit')return folded.encode('ascii', 'surrogateescape')def _fold(self, name, value, sanitize):parts = []parts.append('%s: ' % name)if isinstance(value, str):if _has_surrogates(value):if sanitize:h = header.Header(value,charset=_charset.UNKNOWN8BIT,header_name=name)else:# If we have raw 8bit data in a byte string, we have no idea# what the encoding is. There is no safe way to split this# string. If it's ascii-subset, then we could do a normal# ascii split, but if it's multibyte then we could break the# string. There's no way to know so the least harm seems to# be to not split the string and risk it being too long.parts.append(value)h = Noneelse:h = header.Header(value, header_name=name)else:# Assume it is a Header-like object.h = valueif h is not None:# The Header class interprets a value of None for maxlinelen as the# default value of 78, as recommended by RFC 2822.maxlinelen = 0if self.max_line_length is not None:maxlinelen = self.max_line_lengthparts.append(h.encode(linesep=self.linesep, maxlinelen=maxlinelen))parts.append(self.linesep)return ''.join(parts)compat32 = Compat32()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。