blob: 1e1f66692feb74efdc6f2ddde08bb0978c7d5f09 [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
Barry Warsawca53c122003-03-12 02:54:17 +000010False = 0
11True = 1
12
Barry Warsaw8c1aac22002-05-19 23:44:19 +000013
14
15# This function will become a method of the Message class
16def walk(self):
17 """Walk over the message tree, yielding each subpart.
18
19 The walk is performed in depth-first order. This method is a
20 generator.
21 """
22 parts = []
23 parts.append(self)
24 if self.is_multipart():
25 for subpart in self.get_payload():
26 parts.extend(subpart.walk())
27 return parts
28
29
Barry Warsawff492792002-06-02 18:59:06 +000030# Python 2.2 spells floor division //
31def _floordiv(i, j):
32 """Do a floor division, i/j."""
33 return i / j
Barry Warsaw8c1aac22002-05-19 23:44:19 +000034
35
Barry Warsaw356afac2002-09-10 16:09:06 +000036def _isstring(obj):
Tim Peters6578dc92002-12-24 18:31:27 +000037 return isinstance(obj, StringType) or isinstance(obj, UnicodeType)
Barry Warsaw356afac2002-09-10 16:09:06 +000038
39
Barry Warsaw8c1aac22002-05-19 23:44:19 +000040
41# These two functions are imported into the Iterators.py interface module.
42# The Python 2.2 version uses generators for efficiency.
Barry Warsaw12dc2302003-03-11 04:41:35 +000043def body_line_iterator(msg, decode=False):
44 """Iterate over the parts, returning string payloads line-by-line.
45
46 Optional decode (default False) is passed through to .get_payload().
47 """
Barry Warsaw8c1aac22002-05-19 23:44:19 +000048 lines = []
49 for subpart in msg.walk():
Barry Warsaw12dc2302003-03-11 04:41:35 +000050 payload = subpart.get_payload(decode=decode)
Barry Warsaw356afac2002-09-10 16:09:06 +000051 if _isstring(payload):
Barry Warsaw8c1aac22002-05-19 23:44:19 +000052 for line in StringIO(payload).readlines():
53 lines.append(line)
54 return lines
55
56
57def typed_subpart_iterator(msg, maintype='text', subtype=None):
58 """Iterate over the subparts with a given MIME type.
59
60 Use `maintype' as the main MIME type to match against; this defaults to
61 "text". Optional `subtype' is the MIME subtype to match against; if
62 omitted, only the main type is matched.
63 """
64 parts = []
65 for subpart in msg.walk():
Barry Warsaw8af56772003-03-26 17:56:21 +000066 if subpart.get_content_maintype() == maintype:
67 if subtype is None or subpart.get_content_subtype() == subtype:
Barry Warsaw8c1aac22002-05-19 23:44:19 +000068 parts.append(subpart)
69 return parts