home *** CD-ROM | disk | FTP | other *** search
/ Freelog 33 / Freelog033.iso / Progr / Python-2.2.1.exe / ENCODERS.PY < prev    next >
Encoding:
Python Source  |  2001-10-04  |  1.7 KB  |  70 lines

  1. # Copyright (C) 2001 Python Software Foundation
  2. # Author: barry@zope.com (Barry Warsaw)
  3.  
  4. """Module containing encoding functions for Image.Image and Text.Text.
  5. """
  6.  
  7. import base64
  8. from quopri import encodestring as _encodestring
  9.  
  10.  
  11.  
  12. # Helpers
  13. def _qencode(s):
  14.     return _encodestring(s, quotetabs=1)
  15.  
  16.  
  17. def _bencode(s):
  18.     # We can't quite use base64.encodestring() since it tacks on a "courtesy
  19.     # newline".  Blech!
  20.     if not s:
  21.         return s
  22.     hasnewline = (s[-1] == '\n')
  23.     value = base64.encodestring(s)
  24.     if not hasnewline and value[-1] == '\n':
  25.         return value[:-1]
  26.     return value
  27.  
  28.  
  29.  
  30. def encode_base64(msg):
  31.     """Encode the message's payload in Base64.
  32.  
  33.     Also, add an appropriate Content-Transfer-Encoding: header.
  34.     """
  35.     orig = msg.get_payload()
  36.     encdata = _bencode(orig)
  37.     msg.set_payload(encdata)
  38.     msg['Content-Transfer-Encoding'] = 'base64'
  39.  
  40.  
  41.  
  42. def encode_quopri(msg):
  43.     """Encode the message's payload in Quoted-Printable.
  44.  
  45.     Also, add an appropriate Content-Transfer-Encoding: header.
  46.     """
  47.     orig = msg.get_payload()
  48.     encdata = _qencode(orig)
  49.     msg.set_payload(encdata)
  50.     msg['Content-Transfer-Encoding'] = 'quoted-printable'
  51.  
  52.  
  53.  
  54. def encode_7or8bit(msg):
  55.     """Set the Content-Transfer-Encoding: header to 7bit or 8bit."""
  56.     orig = msg.get_payload()
  57.     # We play a trick to make this go fast.  If encoding to ASCII succeeds, we
  58.     # know the data must be 7bit, otherwise treat it as 8bit.
  59.     try:
  60.         orig.encode('ascii')
  61.     except UnicodeError:
  62.         msg['Content-Transfer-Encoding'] = '8bit'
  63.     else:
  64.         msg['Content-Transfer-Encoding'] = '7bit'
  65.  
  66.  
  67.  
  68. def encode_noop(msg):
  69.     """Do nothing."""
  70.