blob: 932de484e379a36217da23030cdd8d92ac3cb9f4 [file] [log] [blame]
Barry Warsaw8c1aac22002-05-19 23:44:19 +00001# Copyright (C) 2002 Python Software Foundation
2# Author: barry@zope.com
3
4"""Module containing compatibility functions for Python 2.1.
5"""
6
7from cStringIO import StringIO
8from types import StringType, UnicodeType
9
10
11
12# This function will become a method of the Message class
13def walk(self):
14 """Walk over the message tree, yielding each subpart.
15
16 The walk is performed in depth-first order. This method is a
17 generator.
18 """
19 parts = []
20 parts.append(self)
21 if self.is_multipart():
22 for subpart in self.get_payload():
23 parts.extend(subpart.walk())
24 return parts
25
26
27# Used internally by the Header class
28def _intdiv2(i):
29 """Do an integer divide by 2."""
30 return i / 2
31
32
33
34# These two functions are imported into the Iterators.py interface module.
35# The Python 2.2 version uses generators for efficiency.
36def body_line_iterator(msg):
37 """Iterate over the parts, returning string payloads line-by-line."""
38 lines = []
39 for subpart in msg.walk():
40 payload = subpart.get_payload()
41 if isinstance(payload, StringType) or isinstance(payload, UnicodeType):
42 for line in StringIO(payload).readlines():
43 lines.append(line)
44 return lines
45
46
47def typed_subpart_iterator(msg, maintype='text', subtype=None):
48 """Iterate over the subparts with a given MIME type.
49
50 Use `maintype' as the main MIME type to match against; this defaults to
51 "text". Optional `subtype' is the MIME subtype to match against; if
52 omitted, only the main type is matched.
53 """
54 parts = []
55 for subpart in msg.walk():
56 if subpart.get_main_type('text') == maintype:
57 if subtype is None or subpart.get_subtype('plain') == subtype:
58 parts.append(subpart)
59 return parts