blob: b5502ee975266ba17a3dbff387a82b9f3a8040e6 [file] [log] [blame]
Guido van Rossum8b3febe2007-08-30 01:15:14 +00001# Copyright (C) 2001-2006 Python Software Foundation
2# Author: Barry Warsaw
3# Contact: email-sig@python.org
4
5"""Various types of useful iterators and generators."""
6
7__all__ = [
8 'body_line_iterator',
9 'typed_subpart_iterator',
10 'walk',
11 # Do not include _structure() since it's part of the debugging API.
12 ]
13
14import sys
15from io import StringIO
16
17
18
19# This function will become a method of the Message class
20def walk(self):
21 """Walk over the message tree, yielding each subpart.
22
23 The walk is performed in depth-first order. This method is a
24 generator.
25 """
26 yield self
27 if self.is_multipart():
28 for subpart in self.get_payload():
Philip Jenvey4993cc02012-10-01 12:53:43 -070029 yield from subpart.walk()
Guido van Rossum8b3febe2007-08-30 01:15:14 +000030
31
32
33# These two functions are imported into the Iterators.py interface module.
34def body_line_iterator(msg, decode=False):
35 """Iterate over the parts, returning string payloads line-by-line.
36
37 Optional decode (default False) is passed through to .get_payload().
38 """
39 for subpart in msg.walk():
40 payload = subpart.get_payload(decode=decode)
Guido van Rossum3172c5d2007-10-16 18:12:55 +000041 if isinstance(payload, str):
Philip Jenvey4993cc02012-10-01 12:53:43 -070042 yield from StringIO(payload)
Guido van Rossum8b3febe2007-08-30 01:15:14 +000043
44
45def typed_subpart_iterator(msg, maintype='text', subtype=None):
46 """Iterate over the subparts with a given MIME type.
47
48 Use `maintype' as the main MIME type to match against; this defaults to
49 "text". Optional `subtype' is the MIME subtype to match against; if
50 omitted, only the main type is matched.
51 """
52 for subpart in msg.walk():
53 if subpart.get_content_maintype() == maintype:
54 if subtype is None or subpart.get_content_subtype() == subtype:
55 yield subpart
56
57
58
59def _structure(msg, fp=None, level=0, include_default=False):
60 """A handy debugging aid"""
61 if fp is None:
62 fp = sys.stdout
63 tab = ' ' * (level * 4)
64 print(tab + msg.get_content_type(), end='', file=fp)
65 if include_default:
66 print(' [%s]' % msg.get_default_type(), file=fp)
67 else:
68 print(file=fp)
69 if msg.is_multipart():
70 for subpart in msg.get_payload():
71 _structure(subpart, fp, level+1, include_default)