Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/future/backports/email/iterators.py: 32%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

37 statements  

1# 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.""" 

6from __future__ import print_function 

7from __future__ import unicode_literals 

8from __future__ import division 

9from __future__ import absolute_import 

10 

11__all__ = [ 

12 'body_line_iterator', 

13 'typed_subpart_iterator', 

14 'walk', 

15 # Do not include _structure() since it's part of the debugging API. 

16 ] 

17 

18import sys 

19from io import StringIO 

20 

21 

22# This function will become a method of the Message class 

23def walk(self): 

24 """Walk over the message tree, yielding each subpart. 

25 

26 The walk is performed in depth-first order. This method is a 

27 generator. 

28 """ 

29 yield self 

30 if self.is_multipart(): 

31 for subpart in self.get_payload(): 

32 for subsubpart in subpart.walk(): 

33 yield subsubpart 

34 

35 

36# These two functions are imported into the Iterators.py interface module. 

37def body_line_iterator(msg, decode=False): 

38 """Iterate over the parts, returning string payloads line-by-line. 

39 

40 Optional decode (default False) is passed through to .get_payload(). 

41 """ 

42 for subpart in msg.walk(): 

43 payload = subpart.get_payload(decode=decode) 

44 if isinstance(payload, str): 

45 for line in StringIO(payload): 

46 yield line 

47 

48 

49def typed_subpart_iterator(msg, maintype='text', subtype=None): 

50 """Iterate over the subparts with a given MIME type. 

51 

52 Use `maintype' as the main MIME type to match against; this defaults to 

53 "text". Optional `subtype' is the MIME subtype to match against; if 

54 omitted, only the main type is matched. 

55 """ 

56 for subpart in msg.walk(): 

57 if subpart.get_content_maintype() == maintype: 

58 if subtype is None or subpart.get_content_subtype() == subtype: 

59 yield subpart 

60 

61 

62def _structure(msg, fp=None, level=0, include_default=False): 

63 """A handy debugging aid""" 

64 if fp is None: 

65 fp = sys.stdout 

66 tab = ' ' * (level * 4) 

67 print(tab + msg.get_content_type(), end='', file=fp) 

68 if include_default: 

69 print(' [%s]' % msg.get_default_type(), file=fp) 

70 else: 

71 print(file=fp) 

72 if msg.is_multipart(): 

73 for subpart in msg.get_payload(): 

74 _structure(subpart, fp, level+1, include_default)