Python mimetools 模块,decode() 实例源码

我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用mimetools.decode()

项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        """Return the message's body text as string.  This undoes a
        Content-Transfer-Encoding, but does not interpret other MIME
        features (e.g. multipart messages).  To suppress decoding,
        pass 0 as an argument."""
        self.fp.seek(self.startofbody)
        encoding = self.getencoding()
        if not decode or encoding in ('', '7bit', '8bit', 'binary'):
            return self.fp.read()
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        output = StringIO()
        mimetools.decode(self.fp, output, encoding)
        return output.getvalue()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        """Return the message's body text as string.  This undoes a
        Content-Transfer-Encoding, but does not interpret other MIME
        features (e.g. multipart messages).  To suppress decoding,
        pass 0 as an argument."""
        self.fp.seek(self.startofbody)
        encoding = self.getencoding()
        if not decode or encoding in ('', '7bit', '8bit', 'binary'):
            return self.fp.read()
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        output = StringIO()
        mimetools.decode(self.fp, output, encoding)
        return output.getvalue()
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        """Return the message's body text as string.  This undoes a
        Content-Transfer-Encoding, but does not interpret other MIME
        features (e.g. multipart messages).  To suppress decoding,
        pass 0 as an argument."""
        self.fp.seek(self.startofbody)
        encoding = self.getencoding()
        if not decode or encoding in ('', '7bit', '8bit', 'binary'):
            return self.fp.read()
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        output = StringIO()
        mimetools.decode(self.fp, output, encoding)
        return output.getvalue()
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        """Return the message's body text as string.  This undoes a
        Content-Transfer-Encoding, but does not interpret other MIME
        features (e.g. multipart messages).  To suppress decoding,
        pass 0 as an argument."""
        self.fp.seek(self.startofbody)
        encoding = self.getencoding()
        if not decode or encoding in ('', '7bit', '8bit', 'binary'):
            return self.fp.read()
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        output = StringIO()
        mimetools.decode(self.fp, output, encoding)
        return output.getvalue()
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        """Return the message's body text as string.  This undoes a
        Content-Transfer-Encoding, but does not interpret other MIME
        features (e.g. multipart messages).  To suppress decoding,
        pass 0 as an argument."""
        self.fp.seek(self.startofbody)
        encoding = self.getencoding()
        if not decode or encoding in ('', '7bit', '8bit', 'binary'):
            return self.fp.read()
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        output = StringIO()
        mimetools.decode(self.fp, output, encoding)
        return output.getvalue()
项目:anki-onenote-importer    作者:tmpethick    | 项目源码 | 文件源码
def text(message):
        """Returns the plain text of the message. If the message is multipart search
        for an attachment with no filename and with mimetype `text/plain` and returns
        it.

        Parameters
        ----------
        message: email.message.Message
            Message to decode.

        Returns
        -------
        message_text: str
            Returns the plain text of the message. This method will try return the text
            encoded to `utf-8`. If it can't, returns it with its original encoding. If
            it can't find the text returns `None`.

        Raises
        ------
        TypeError
            If the parameter is not an instance of :class:`email.message.Message`.
        """
        return Text.decoded(message, ['text/plain'])
项目:anki-onenote-importer    作者:tmpethick    | 项目源码 | 文件源码
def html(message):
        """Returns the html of the message. If the message is multipart search for an
        attachment with no filename and with mimetype `text/html` and returns it.

        Parameters
        ----------
        message: email.message.Message
            Message to decode.

        Returns
        -------
        message_text: str
            Returns the html of the message. This method will try return the html
            encoded to `utf-8`. If it can't, returns it with its original encoding. If
            it can't find the text returns `None`.

        Raises
        ------
        TypeError
            If the parameter is not an instance of :class:`email.message.Message`.
        """
        return Text.decoded(message, ['text/html'])
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        """Return the message's body text as string.  This undoes a
        Content-Transfer-Encoding, but does not interpret other MIME
        features (e.g. multipart messages).  To suppress decoding,
        pass 0 as an argument."""
        self.fp.seek(self.startofbody)
        encoding = self.getencoding()
        if not decode or encoding in ('', '7bit', '8bit', 'binary'):
            return self.fp.read()
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        output = StringIO()
        mimetools.decode(self.fp, output, encoding)
        return output.getvalue()
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        """Return the message's body text as string.  This undoes a
        Content-Transfer-Encoding, but does not interpret other MIME
        features (e.g. multipart messages).  To suppress decoding,
        pass 0 as an argument."""
        self.fp.seek(self.startofbody)
        encoding = self.getencoding()
        if not decode or encoding in ('', '7bit', '8bit', 'binary'):
            return self.fp.read()
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        output = StringIO()
        mimetools.decode(self.fp, output, encoding)
        return output.getvalue()
项目:empyrion-python-api    作者:huhlig    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        """Return the message's body text as string.  This undoes a
        Content-Transfer-Encoding, but does not interpret other MIME
        features (e.g. multipart messages).  To suppress decoding,
        pass 0 as an argument."""
        self.fp.seek(self.startofbody)
        encoding = self.getencoding()
        if not decode or encoding in ('', '7bit', '8bit', 'binary'):
            return self.fp.read()
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        output = StringIO()
        mimetools.decode(self.fp, output, encoding)
        return output.getvalue()
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def __init__(self, f, n, fp):
        """Constructor."""
        Message.__init__(self, f, n, fp)
        if self.getmaintype() == 'multipart':
            self.body = Message.getbodyparts(self)
        else:
            self.body = Message.getbodytext(self)
        self.bodyencoded = Message.getbodytext(self, decode=0)
            # XXX If this is big, should remember file pointers
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        if not decode:
            return self.bodyencoded
        if type(self.body) == type(''):
            return self.body
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, f, n, fp):
        """Constructor."""
        Message.__init__(self, f, n, fp)
        if self.getmaintype() == 'multipart':
            self.body = Message.getbodyparts(self)
        else:
            self.body = Message.getbodytext(self)
        self.bodyencoded = Message.getbodytext(self, decode=0)
            # XXX If this is big, should remember file pointers
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        if not decode:
            return self.bodyencoded
        if type(self.body) == type(''):
            return self.body
项目:vspheretools    作者:devopshq    | 项目源码 | 文件源码
def Opaque(uri, tc, ps, **keywords):
    '''Resolve a URI and return its content as a string.
    '''
    source = urllib.urlopen(uri, **keywords)
    enc = source.info().getencoding()
    if enc in ['7bit', '8bit', 'binary']: return source.read()

    data = StringIO.StringIO()
    mimetools.decode(source, data, enc)
    return data.getvalue()
项目:vspheretools    作者:devopshq    | 项目源码 | 文件源码
def XML(uri, tc, ps, **keywords):
    '''Resolve a URI and return its content as an XML DOM.
    '''
    source = urllib.urlopen(uri, **keywords)
    enc = source.info().getencoding()
    if enc in ['7bit', '8bit', 'binary']:
        data = source
    else:
        data = StringIO.StringIO()
        mimetools.decode(source, data, enc)
        data.seek(0)
    dom = ps.readerclass().fromStream(data)
    return _child_elements(dom)[0]
项目:vspheretools    作者:devopshq    | 项目源码 | 文件源码
def __init__(self, ct, f, next=None, uribase='thismessage:/',
    seekable=0, **kw):
        # Get the boundary.  It's too bad I have to write this myself,
        # but no way am I going to import cgi for 10 lines of code!
        for param in ct.split(';'):
            a = param.strip()
            if a.startswith('boundary='):
                if a[9] in [ '"', "'" ]:
                    boundary = a[10:-1]
                else:
                    boundary = a[9:]
                break
        else:
            raise ValueError('boundary parameter not found')

        self.id_dict, self.loc_dict, self.parts = {}, {}, []
        self.next = next
        self.base = uribase

        mf = multifile.MultiFile(f, seekable)
        mf.push(boundary)
        while mf.next():
            head = mimetools.Message(mf)
            body = StringIO.StringIO()
            mimetools.decode(mf, body, head.getencoding())
            body.seek(0)
            part = (head, body)
            self.parts.append(part)
            key = head.get('content-id')
            if key:
                if key[0] == '<' and key[-1] == '>': key = key[1:-1]
                self.id_dict[key] = part
            key = head.get('content-location')
            if key: self.loc_dict[key] = part
        mf.pop()
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def __init__(self, f, n, fp):
        """Constructor."""
        Message.__init__(self, f, n, fp)
        if self.getmaintype() == 'multipart':
            self.body = Message.getbodyparts(self)
        else:
            self.body = Message.getbodytext(self)
        self.bodyencoded = Message.getbodytext(self, decode=0)
            # XXX If this is big, should remember file pointers
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        if not decode:
            return self.bodyencoded
        if type(self.body) == type(''):
            return self.body
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def __init__(self, f, n, fp):
        """Constructor."""
        Message.__init__(self, f, n, fp)
        if self.getmaintype() == 'multipart':
            self.body = Message.getbodyparts(self)
        else:
            self.body = Message.getbodytext(self)
        self.bodyencoded = Message.getbodytext(self, decode=0)
            # XXX If this is big, should remember file pointers
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        if not decode:
            return self.bodyencoded
        if type(self.body) == type(''):
            return self.body
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def __init__(self, f, n, fp):
        """Constructor."""
        Message.__init__(self, f, n, fp)
        if self.getmaintype() == 'multipart':
            self.body = Message.getbodyparts(self)
        else:
            self.body = Message.getbodytext(self)
        self.bodyencoded = Message.getbodytext(self, decode=0)
            # XXX If this is big, should remember file pointers
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        if not decode:
            return self.bodyencoded
        if type(self.body) == type(''):
            return self.body
项目:anki-onenote-importer    作者:tmpethick    | 项目源码 | 文件源码
def decode_content(message):
        """Decode the content of a message. This method do not checks if the message is
        multipart or if the message mime type is plain text or html.

        Parameters
        ----------
        message: email.message.Message
            Message to decode.

        Returns
        -------
        content: str
            Decoded content of the message

        Raises
        ------
        TypeError
            If the parameter is not an instance of :class:`email.message.Message`.
        """
        if not isinstance(message, email.message.Message):
            raise TypeError("Expected a message object.")
        encoding = message['Content-Transfer-Encoding']
        if encoding and encoding.strip() == 'quoted-printable':
            result = message.get_payload()
            stream = cStringIO.StringIO(result)
            output = cStringIO.StringIO()
            mimetools.decode(stream, output, 'quoted-printable')
            return output.getvalue()
        return message.get_payload(decode=True)
项目:anki-onenote-importer    作者:tmpethick    | 项目源码 | 文件源码
def decode_text(message):
        """Extracts the text of the message and try to convert it to utf-8. This method
        do not checks if the message is multipart or if the message mime type is plain
        text or html. Maybe you want to use the methods :class:`Text.text` and
        :class:`Text.html`.

        Parameters
        ----------
        message: email.message.Message
            Message to extract its text.

        Returns
        -------
        content: str
            Text of the message encoded to utf-8. If it cannot encode the text to utf-8
            the text will be returned as ascii.

        Raises
        ------
        TypeError
            If the parameter is not an instance of :class:`email.message.Message`.
        """
        def utf8(text):
            try:
                charset = message.get_content_charset()
                if charset:
                    return text.decode(charset).encode('utf-8')
            except LookupError:
                return text
            except (UnicodeDecodeError, UnicodeEncodeError):
                return text
            return text
        try:
            return utf8(Text.decode_content(message))
        except (UnicodeDecodeError, UnicodeEncodeError):
            return message.get_payload().encode('ascii')
项目:anki-onenote-importer    作者:tmpethick    | 项目源码 | 文件源码
def undecoded_text(message):
        """
        This method is similar to :class:`Text.text` but it doesn't try to decode the
        returned text.
        """
        return Text.undecoded(message, ['text/plain'])
项目:anki-onenote-importer    作者:tmpethick    | 项目源码 | 文件源码
def undecoded_html(message):
        """
        This method is similar to :class:`Text.html` but it doesn't try to decode the
        returned text.
        """
        return Text.undecoded(message, ['text/html'])
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def __init__(self, f, n, fp):
        """Constructor."""
        Message.__init__(self, f, n, fp)
        if self.getmaintype() == 'multipart':
            self.body = Message.getbodyparts(self)
        else:
            self.body = Message.getbodytext(self)
        self.bodyencoded = Message.getbodytext(self, decode=0)
            # XXX If this is big, should remember file pointers
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        if not decode:
            return self.bodyencoded
        if type(self.body) == type(''):
            return self.body
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def __init__(self, f, n, fp):
        """Constructor."""
        Message.__init__(self, f, n, fp)
        if self.getmaintype() == 'multipart':
            self.body = Message.getbodyparts(self)
        else:
            self.body = Message.getbodytext(self)
        self.bodyencoded = Message.getbodytext(self, decode=0)
            # XXX If this is big, should remember file pointers
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        if not decode:
            return self.bodyencoded
        if type(self.body) == type(''):
            return self.body
项目:empyrion-python-api    作者:huhlig    | 项目源码 | 文件源码
def __init__(self, f, n, fp):
        """Constructor."""
        Message.__init__(self, f, n, fp)
        if self.getmaintype() == 'multipart':
            self.body = Message.getbodyparts(self)
        else:
            self.body = Message.getbodytext(self)
        self.bodyencoded = Message.getbodytext(self, decode=0)
            # XXX If this is big, should remember file pointers
项目:empyrion-python-api    作者:huhlig    | 项目源码 | 文件源码
def getbodytext(self, decode = 1):
        if not decode:
            return self.bodyencoded
        if type(self.body) == type(''):
            return self.body
项目:anki-onenote-importer    作者:tmpethick    | 项目源码 | 文件源码
def decoded(message, allowed_mimetypes=None):
        """
        If the mimetype of the message is in the `allowed_mimetypes` parameter returns
        returns its content decoded. If the message is multipart find in the attachments
        a message with mimetype in the `allowed_mimetypes` parameter and returns its
        content decoded.

        Parameters
        ----------
        message: email.message.Message
            Message to decode.
        allowed_mimetypes: iterable
            Iterable object with the mimetypes will be used the select the message to
            extract its text. Only `text/plain` and `text/html` allowed or a
            `ValueError` exception will be raised.

        Returns
        -------
        message_text: str
            Returns the plain text of the message. This method will try return the text
            encoded to `utf-8`. If it can't, returns it with its original encoding. If
            it can't find the text returns `None`.

        Raises
        ------
        TypeError
            If the parameter is not an instance of :class:`email.message.Message`.
        ValueError
            If the value in the parameter allowed_mimetypes is incorrect.
        """
        if allowed_mimetypes is None:
            allowed_mimetypes = ('text/plain', 'text/html')
        wrong_mime_types = frozenset(allowed_mimetypes).difference(['text/plain', 'text/html'])
        if wrong_mime_types:
            raise ValueError("Wrong mime types: {0}".format(list(wrong_mime_types)))
        if not isinstance(message, email.message.Message):
            raise TypeError("Expected a message object.")
        if not message.is_multipart():
            if message.get_filename():
                return None
            if message.get_content_type() in allowed_mimetypes:
                return (Text.decode_text(message), 
                    message.get('Content-Location'))
            return None
        for sub_message in message.get_payload():
            if not sub_message.is_multipart() or sub_message.get_content_type() == 'multipart/alternative':
                result = Text.decoded(sub_message)
                if result:
                    return result
        return None