Barry Warsaw | 409a4c0 | 2002-04-10 21:01:31 +0000 | [diff] [blame] | 1 | # Copyright (C) 2001,2002 Python Software Foundation |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 2 | # Author: barry@zope.com (Barry Warsaw) |
| 3 | |
| 4 | """Classes to generate plain text from a message object tree. |
| 5 | """ |
| 6 | |
| 7 | import time |
| 8 | import re |
| 9 | import random |
| 10 | |
Barry Warsaw | 6c2bc46 | 2002-10-14 15:09:30 +0000 | [diff] [blame] | 11 | from types import ListType, StringType |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 12 | from cStringIO import StringIO |
| 13 | |
Barry Warsaw | 062749a | 2002-06-28 23:41:42 +0000 | [diff] [blame] | 14 | from email.Header import Header |
| 15 | |
Barry Warsaw | b1c1de3 | 2002-09-10 16:13:45 +0000 | [diff] [blame] | 16 | try: |
| 17 | from email._compat22 import _isstring |
| 18 | except SyntaxError: |
| 19 | from email._compat21 import _isstring |
| 20 | |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 21 | try: |
| 22 | True, False |
| 23 | except NameError: |
| 24 | True = 1 |
| 25 | False = 0 |
Barry Warsaw | b1c1de3 | 2002-09-10 16:13:45 +0000 | [diff] [blame] | 26 | |
Barry Warsaw | d1eeecb | 2001-10-17 20:51:42 +0000 | [diff] [blame] | 27 | EMPTYSTRING = '' |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 28 | SEMISPACE = '; ' |
| 29 | BAR = '|' |
| 30 | UNDERSCORE = '_' |
| 31 | NL = '\n' |
Barry Warsaw | d1eeecb | 2001-10-17 20:51:42 +0000 | [diff] [blame] | 32 | NLTAB = '\n\t' |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 33 | SEMINLTAB = ';\n\t' |
| 34 | SPACE8 = ' ' * 8 |
| 35 | |
| 36 | fcre = re.compile(r'^From ', re.MULTILINE) |
| 37 | |
Barry Warsaw | 6c2bc46 | 2002-10-14 15:09:30 +0000 | [diff] [blame] | 38 | def _is8bitstring(s): |
| 39 | if isinstance(s, StringType): |
| 40 | try: |
| 41 | unicode(s, 'us-ascii') |
| 42 | except UnicodeError: |
| 43 | return True |
| 44 | return False |
| 45 | |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 46 | |
Barry Warsaw | e968ead | 2001-10-04 17:05:11 +0000 | [diff] [blame] | 47 | |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 48 | class Generator: |
| 49 | """Generates output from a Message object tree. |
| 50 | |
| 51 | This basic generator writes the message to the given file object as plain |
| 52 | text. |
| 53 | """ |
| 54 | # |
| 55 | # Public interface |
| 56 | # |
| 57 | |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 58 | def __init__(self, outfp, mangle_from_=True, maxheaderlen=78): |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 59 | """Create the generator for message flattening. |
| 60 | |
| 61 | outfp is the output file-like object for writing the message to. It |
| 62 | must have a write() method. |
| 63 | |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 64 | Optional mangle_from_ is a flag that, when True (the default), escapes |
| 65 | From_ lines in the body of the message by putting a `>' in front of |
| 66 | them. |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 67 | |
| 68 | Optional maxheaderlen specifies the longest length for a non-continued |
| 69 | header. When a header line is longer (in characters, with tabs |
| 70 | expanded to 8 spaces), than maxheaderlen, the header will be broken on |
| 71 | semicolons and continued as per RFC 2822. If no semicolon is found, |
| 72 | then the header is left alone. Set to zero to disable wrapping |
| 73 | headers. Default is 78, as recommended (but not required by RFC |
| 74 | 2822. |
| 75 | """ |
| 76 | self._fp = outfp |
| 77 | self._mangle_from_ = mangle_from_ |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 78 | self.__maxheaderlen = maxheaderlen |
| 79 | |
| 80 | def write(self, s): |
| 81 | # Just delegate to the file object |
| 82 | self._fp.write(s) |
| 83 | |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 84 | def flatten(self, msg, unixfrom=False): |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 85 | """Print the message object tree rooted at msg to the output file |
| 86 | specified when the Generator instance was created. |
| 87 | |
| 88 | unixfrom is a flag that forces the printing of a Unix From_ delimiter |
| 89 | before the first object in the message tree. If the original message |
| 90 | has no From_ delimiter, a `standard' one is crafted. By default, this |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 91 | is False to inhibit the printing of any From_ delimiter. |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 92 | |
| 93 | Note that for subobjects, no From_ line is printed. |
| 94 | """ |
| 95 | if unixfrom: |
| 96 | ufrom = msg.get_unixfrom() |
| 97 | if not ufrom: |
| 98 | ufrom = 'From nobody ' + time.ctime(time.time()) |
| 99 | print >> self._fp, ufrom |
| 100 | self._write(msg) |
| 101 | |
Barry Warsaw | 7dc865a | 2002-06-02 19:02:37 +0000 | [diff] [blame] | 102 | # For backwards compatibility, but this is slower |
| 103 | __call__ = flatten |
| 104 | |
Barry Warsaw | 93c40f0 | 2002-07-09 02:43:47 +0000 | [diff] [blame] | 105 | def clone(self, fp): |
| 106 | """Clone this generator with the exact same options.""" |
| 107 | return self.__class__(fp, self._mangle_from_, self.__maxheaderlen) |
| 108 | |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 109 | # |
| 110 | # Protected interface - undocumented ;/ |
| 111 | # |
| 112 | |
| 113 | def _write(self, msg): |
| 114 | # We can't write the headers yet because of the following scenario: |
| 115 | # say a multipart message includes the boundary string somewhere in |
| 116 | # its body. We'd have to calculate the new boundary /before/ we write |
| 117 | # the headers so that we can write the correct Content-Type: |
| 118 | # parameter. |
| 119 | # |
| 120 | # The way we do this, so as to make the _handle_*() methods simpler, |
| 121 | # is to cache any subpart writes into a StringIO. The we write the |
| 122 | # headers and the StringIO contents. That way, subpart handlers can |
| 123 | # Do The Right Thing, and can still modify the Content-Type: header if |
| 124 | # necessary. |
| 125 | oldfp = self._fp |
| 126 | try: |
| 127 | self._fp = sfp = StringIO() |
| 128 | self._dispatch(msg) |
| 129 | finally: |
| 130 | self._fp = oldfp |
| 131 | # Write the headers. First we see if the message object wants to |
| 132 | # handle that itself. If not, we'll do it generically. |
| 133 | meth = getattr(msg, '_write_headers', None) |
| 134 | if meth is None: |
| 135 | self._write_headers(msg) |
| 136 | else: |
| 137 | meth(self) |
| 138 | self._fp.write(sfp.getvalue()) |
| 139 | |
| 140 | def _dispatch(self, msg): |
| 141 | # Get the Content-Type: for the message, then try to dispatch to |
Barry Warsaw | f488b2c | 2002-07-11 18:48:40 +0000 | [diff] [blame] | 142 | # self._handle_<maintype>_<subtype>(). If there's no handler for the |
| 143 | # full MIME type, then dispatch to self._handle_<maintype>(). If |
| 144 | # that's missing too, then dispatch to self._writeBody(). |
Barry Warsaw | dfea3b3 | 2002-08-20 14:47:30 +0000 | [diff] [blame] | 145 | main = msg.get_content_maintype() |
| 146 | sub = msg.get_content_subtype() |
Barry Warsaw | 93c40f0 | 2002-07-09 02:43:47 +0000 | [diff] [blame] | 147 | specific = UNDERSCORE.join((main, sub)).replace('-', '_') |
| 148 | meth = getattr(self, '_handle_' + specific, None) |
| 149 | if meth is None: |
| 150 | generic = main.replace('-', '_') |
| 151 | meth = getattr(self, '_handle_' + generic, None) |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 152 | if meth is None: |
Barry Warsaw | 93c40f0 | 2002-07-09 02:43:47 +0000 | [diff] [blame] | 153 | meth = self._writeBody |
| 154 | meth(msg) |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 155 | |
| 156 | # |
| 157 | # Default handlers |
| 158 | # |
| 159 | |
| 160 | def _write_headers(self, msg): |
| 161 | for h, v in msg.items(): |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 162 | # RFC 2822 says that lines SHOULD be no more than maxheaderlen |
| 163 | # characters wide, so we're well within our rights to split long |
| 164 | # headers. |
| 165 | text = '%s: %s' % (h, v) |
| 166 | if self.__maxheaderlen > 0 and len(text) > self.__maxheaderlen: |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 167 | text = self._split_header(text) |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 168 | print >> self._fp, text |
| 169 | # A blank line always separates headers from body |
| 170 | print >> self._fp |
| 171 | |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 172 | def _split_header(self, text): |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 173 | maxheaderlen = self.__maxheaderlen |
| 174 | # Find out whether any lines in the header are really longer than |
| 175 | # maxheaderlen characters wide. There could be continuation lines |
| 176 | # that actually shorten it. Also, replace hard tabs with 8 spaces. |
Barry Warsaw | 062749a | 2002-06-28 23:41:42 +0000 | [diff] [blame] | 177 | lines = [s.replace('\t', SPACE8) for s in text.splitlines()] |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 178 | for line in lines: |
| 179 | if len(line) > maxheaderlen: |
| 180 | break |
| 181 | else: |
| 182 | # No line was actually longer than maxheaderlen characters, so |
| 183 | # just return the original unchanged. |
| 184 | return text |
Barry Warsaw | 6c2bc46 | 2002-10-14 15:09:30 +0000 | [diff] [blame] | 185 | # If we have raw 8bit data in a byte string, we have no idea what the |
| 186 | # encoding is. I think there is no safe way to split this string. If |
| 187 | # it's ascii-subset, then we could do a normal ascii split, but if |
| 188 | # it's multibyte then we could break the string. There's no way to |
| 189 | # know so the least harm seems to be to not split the string and risk |
| 190 | # it being too long. |
| 191 | if _is8bitstring(text): |
| 192 | return text |
Barry Warsaw | 062749a | 2002-06-28 23:41:42 +0000 | [diff] [blame] | 193 | # The `text' argument already has the field name prepended, so don't |
| 194 | # provide it here or the first line will get folded too short. |
| 195 | h = Header(text, maxlinelen=maxheaderlen, |
| 196 | # For backwards compatibility, we use a hard tab here |
| 197 | continuation_ws='\t') |
| 198 | return h.encode() |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 199 | |
| 200 | # |
| 201 | # Handlers for writing types and subtypes |
| 202 | # |
| 203 | |
| 204 | def _handle_text(self, msg): |
| 205 | payload = msg.get_payload() |
Barry Warsaw | b384e01 | 2001-09-26 05:32:41 +0000 | [diff] [blame] | 206 | if payload is None: |
| 207 | return |
Barry Warsaw | 409a4c0 | 2002-04-10 21:01:31 +0000 | [diff] [blame] | 208 | cset = msg.get_charset() |
| 209 | if cset is not None: |
| 210 | payload = cset.body_encode(payload) |
Barry Warsaw | b1c1de3 | 2002-09-10 16:13:45 +0000 | [diff] [blame] | 211 | if not _isstring(payload): |
Barry Warsaw | b384e01 | 2001-09-26 05:32:41 +0000 | [diff] [blame] | 212 | raise TypeError, 'string payload expected: %s' % type(payload) |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 213 | if self._mangle_from_: |
| 214 | payload = fcre.sub('>From ', payload) |
| 215 | self._fp.write(payload) |
| 216 | |
| 217 | # Default body handler |
| 218 | _writeBody = _handle_text |
| 219 | |
Barry Warsaw | 93c40f0 | 2002-07-09 02:43:47 +0000 | [diff] [blame] | 220 | def _handle_multipart(self, msg): |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 221 | # The trick here is to write out each part separately, merge them all |
| 222 | # together, and then make sure that the boundary we've chosen isn't |
| 223 | # present in the payload. |
| 224 | msgtexts = [] |
Barry Warsaw | 409a4c0 | 2002-04-10 21:01:31 +0000 | [diff] [blame] | 225 | subparts = msg.get_payload() |
| 226 | if subparts is None: |
Barry Warsaw | 93c40f0 | 2002-07-09 02:43:47 +0000 | [diff] [blame] | 227 | # Nothing has ever been attached |
Barry Warsaw | 409a4c0 | 2002-04-10 21:01:31 +0000 | [diff] [blame] | 228 | boundary = msg.get_boundary(failobj=_make_boundary()) |
| 229 | print >> self._fp, '--' + boundary |
| 230 | print >> self._fp, '\n' |
| 231 | print >> self._fp, '--' + boundary + '--' |
| 232 | return |
Barry Warsaw | b1c1de3 | 2002-09-10 16:13:45 +0000 | [diff] [blame] | 233 | elif _isstring(subparts): |
| 234 | # e.g. a non-strict parse of a message with no starting boundary. |
| 235 | self._fp.write(subparts) |
| 236 | return |
Barry Warsaw | 409a4c0 | 2002-04-10 21:01:31 +0000 | [diff] [blame] | 237 | elif not isinstance(subparts, ListType): |
| 238 | # Scalar payload |
| 239 | subparts = [subparts] |
| 240 | for part in subparts: |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 241 | s = StringIO() |
Barry Warsaw | 93c40f0 | 2002-07-09 02:43:47 +0000 | [diff] [blame] | 242 | g = self.clone(s) |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 243 | g.flatten(part, unixfrom=False) |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 244 | msgtexts.append(s.getvalue()) |
| 245 | # Now make sure the boundary we've selected doesn't appear in any of |
| 246 | # the message texts. |
| 247 | alltext = NL.join(msgtexts) |
| 248 | # BAW: What about boundaries that are wrapped in double-quotes? |
| 249 | boundary = msg.get_boundary(failobj=_make_boundary(alltext)) |
| 250 | # If we had to calculate a new boundary because the body text |
| 251 | # contained that string, set the new boundary. We don't do it |
| 252 | # unconditionally because, while set_boundary() preserves order, it |
| 253 | # doesn't preserve newlines/continuations in headers. This is no big |
| 254 | # deal in practice, but turns out to be inconvenient for the unittest |
| 255 | # suite. |
| 256 | if msg.get_boundary() <> boundary: |
| 257 | msg.set_boundary(boundary) |
| 258 | # Write out any preamble |
| 259 | if msg.preamble is not None: |
| 260 | self._fp.write(msg.preamble) |
| 261 | # First boundary is a bit different; it doesn't have a leading extra |
| 262 | # newline. |
| 263 | print >> self._fp, '--' + boundary |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 264 | # Join and write the individual parts |
| 265 | joiner = '\n--' + boundary + '\n' |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 266 | self._fp.write(joiner.join(msgtexts)) |
| 267 | print >> self._fp, '\n--' + boundary + '--', |
| 268 | # Write out any epilogue |
| 269 | if msg.epilogue is not None: |
Barry Warsaw | 856c32b | 2001-10-19 04:06:39 +0000 | [diff] [blame] | 270 | if not msg.epilogue.startswith('\n'): |
| 271 | print >> self._fp |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 272 | self._fp.write(msg.epilogue) |
| 273 | |
Barry Warsaw | b384e01 | 2001-09-26 05:32:41 +0000 | [diff] [blame] | 274 | def _handle_message_delivery_status(self, msg): |
| 275 | # We can't just write the headers directly to self's file object |
| 276 | # because this will leave an extra newline between the last header |
| 277 | # block and the boundary. Sigh. |
| 278 | blocks = [] |
| 279 | for part in msg.get_payload(): |
| 280 | s = StringIO() |
Barry Warsaw | 93c40f0 | 2002-07-09 02:43:47 +0000 | [diff] [blame] | 281 | g = self.clone(s) |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 282 | g.flatten(part, unixfrom=False) |
Barry Warsaw | b384e01 | 2001-09-26 05:32:41 +0000 | [diff] [blame] | 283 | text = s.getvalue() |
| 284 | lines = text.split('\n') |
| 285 | # Strip off the unnecessary trailing empty line |
| 286 | if lines and lines[-1] == '': |
| 287 | blocks.append(NL.join(lines[:-1])) |
| 288 | else: |
| 289 | blocks.append(text) |
| 290 | # Now join all the blocks with an empty line. This has the lovely |
| 291 | # effect of separating each block with an empty line, but not adding |
| 292 | # an extra one after the last one. |
| 293 | self._fp.write(NL.join(blocks)) |
| 294 | |
| 295 | def _handle_message(self, msg): |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 296 | s = StringIO() |
Barry Warsaw | 93c40f0 | 2002-07-09 02:43:47 +0000 | [diff] [blame] | 297 | g = self.clone(s) |
Barry Warsaw | 7dc865a | 2002-06-02 19:02:37 +0000 | [diff] [blame] | 298 | # The payload of a message/rfc822 part should be a multipart sequence |
| 299 | # of length 1. The zeroth element of the list should be the Message |
Barry Warsaw | 93c40f0 | 2002-07-09 02:43:47 +0000 | [diff] [blame] | 300 | # object for the subpart. Extract that object, stringify it, and |
| 301 | # write it out. |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 302 | g.flatten(msg.get_payload(0), unixfrom=False) |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 303 | self._fp.write(s.getvalue()) |
| 304 | |
| 305 | |
Barry Warsaw | e968ead | 2001-10-04 17:05:11 +0000 | [diff] [blame] | 306 | |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 307 | class DecodedGenerator(Generator): |
| 308 | """Generator a text representation of a message. |
| 309 | |
| 310 | Like the Generator base class, except that non-text parts are substituted |
| 311 | with a format string representing the part. |
| 312 | """ |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 313 | def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None): |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 314 | """Like Generator.__init__() except that an additional optional |
| 315 | argument is allowed. |
| 316 | |
| 317 | Walks through all subparts of a message. If the subpart is of main |
| 318 | type `text', then it prints the decoded payload of the subpart. |
| 319 | |
| 320 | Otherwise, fmt is a format string that is used instead of the message |
| 321 | payload. fmt is expanded with the following keywords (in |
| 322 | %(keyword)s format): |
| 323 | |
| 324 | type : Full MIME type of the non-text part |
| 325 | maintype : Main MIME type of the non-text part |
| 326 | subtype : Sub-MIME type of the non-text part |
| 327 | filename : Filename of the non-text part |
| 328 | description: Description associated with the non-text part |
| 329 | encoding : Content transfer encoding of the non-text part |
| 330 | |
| 331 | The default value for fmt is None, meaning |
| 332 | |
| 333 | [Non-text (%(type)s) part of message omitted, filename %(filename)s] |
| 334 | """ |
| 335 | Generator.__init__(self, outfp, mangle_from_, maxheaderlen) |
| 336 | if fmt is None: |
| 337 | fmt = ('[Non-text (%(type)s) part of message omitted, ' |
| 338 | 'filename %(filename)s]') |
| 339 | self._fmt = fmt |
| 340 | |
| 341 | def _dispatch(self, msg): |
| 342 | for part in msg.walk(): |
Barry Warsaw | b384e01 | 2001-09-26 05:32:41 +0000 | [diff] [blame] | 343 | maintype = part.get_main_type('text') |
| 344 | if maintype == 'text': |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 345 | print >> self, part.get_payload(decode=True) |
Barry Warsaw | b384e01 | 2001-09-26 05:32:41 +0000 | [diff] [blame] | 346 | elif maintype == 'multipart': |
| 347 | # Just skip this |
| 348 | pass |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 349 | else: |
| 350 | print >> self, self._fmt % { |
| 351 | 'type' : part.get_type('[no MIME type]'), |
| 352 | 'maintype' : part.get_main_type('[no main MIME type]'), |
| 353 | 'subtype' : part.get_subtype('[no sub-MIME type]'), |
| 354 | 'filename' : part.get_filename('[no filename]'), |
| 355 | 'description': part.get('Content-Description', |
| 356 | '[no description]'), |
| 357 | 'encoding' : part.get('Content-Transfer-Encoding', |
| 358 | '[no encoding]'), |
| 359 | } |
| 360 | |
| 361 | |
Barry Warsaw | e968ead | 2001-10-04 17:05:11 +0000 | [diff] [blame] | 362 | |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 363 | # Helper |
Barry Warsaw | 409a4c0 | 2002-04-10 21:01:31 +0000 | [diff] [blame] | 364 | def _make_boundary(text=None): |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 365 | # Craft a random boundary. If text is given, ensure that the chosen |
| 366 | # boundary doesn't appear in the text. |
| 367 | boundary = ('=' * 15) + repr(random.random()).split('.')[1] + '==' |
| 368 | if text is None: |
| 369 | return boundary |
| 370 | b = boundary |
| 371 | counter = 0 |
Barry Warsaw | 56835dd | 2002-09-28 18:04:55 +0000 | [diff] [blame] | 372 | while True: |
Barry Warsaw | ba92580 | 2001-09-23 03:17:28 +0000 | [diff] [blame] | 373 | cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE) |
| 374 | if not cre.search(text): |
| 375 | break |
| 376 | b = boundary + '.' + str(counter) |
| 377 | counter += 1 |
| 378 | return b |