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