summaryrefslogtreecommitdiff
path: root/Lib/email/_compat21.py
blob: de8c44753de43601210714d835b08051ac21a9ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# Copyright (C) 2002 Python Software Foundation
# Author: barry@zope.com

"""Module containing compatibility functions for Python 2.1.
"""

from cStringIO import StringIO
from types import StringType, UnicodeType



# This function will become a method of the Message class
def walk(self):
    """Walk over the message tree, yielding each subpart.

    The walk is performed in depth-first order.  This method is a
    generator.
    """
    parts = []
    parts.append(self)
    if self.is_multipart():
        for subpart in self.get_payload():
            parts.extend(subpart.walk())
    return parts


# Python 2.2 spells floor division //
def _floordiv(i, j):
    """Do a floor division, i/j."""
    return i / j


def _isstring(obj):
    return isinstance(obj, StringType) or isinstance(obj, UnicodeType)    



# These two functions are imported into the Iterators.py interface module.
# The Python 2.2 version uses generators for efficiency.
def body_line_iterator(msg):
    """Iterate over the parts, returning string payloads line-by-line."""
    lines = []
    for subpart in msg.walk():
        payload = subpart.get_payload()
        if _isstring(payload):
            for line in StringIO(payload).readlines():
                lines.append(line)
    return lines


def typed_subpart_iterator(msg, maintype='text', subtype=None):
    """Iterate over the subparts with a given MIME type.

    Use `maintype' as the main MIME type to match against; this defaults to
    "text".  Optional `subtype' is the MIME subtype to match against; if
    omitted, only the main type is matched.
    """
    parts = []
    for subpart in msg.walk():
        if subpart.get_main_type('text') == maintype:
            if subtype is None or subpart.get_subtype('plain') == subtype:
                parts.append(subpart)
    return parts