quopri_codec.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Codec for quoted-printable encoding.
  2. Like base64 and rot13, this returns Python strings, not Unicode.
  3. """
  4. import codecs, quopri
  5. try:
  6. from cStringIO import StringIO
  7. except ImportError:
  8. from StringIO import StringIO
  9. def quopri_encode(input, errors='strict'):
  10. """Encode the input, returning a tuple (output object, length consumed).
  11. errors defines the error handling to apply. It defaults to
  12. 'strict' handling which is the only currently supported
  13. error handling for this codec.
  14. """
  15. assert errors == 'strict'
  16. # using str() because of cStringIO's Unicode undesired Unicode behavior.
  17. f = StringIO(str(input))
  18. g = StringIO()
  19. quopri.encode(f, g, quotetabs=True)
  20. output = g.getvalue()
  21. return (output, len(input))
  22. def quopri_decode(input, errors='strict'):
  23. """Decode the input, returning a tuple (output object, length consumed).
  24. errors defines the error handling to apply. It defaults to
  25. 'strict' handling which is the only currently supported
  26. error handling for this codec.
  27. """
  28. assert errors == 'strict'
  29. f = StringIO(str(input))
  30. g = StringIO()
  31. quopri.decode(f, g)
  32. output = g.getvalue()
  33. return (output, len(input))
  34. class Codec(codecs.Codec):
  35. def encode(self, input,errors='strict'):
  36. return quopri_encode(input,errors)
  37. def decode(self, input,errors='strict'):
  38. return quopri_decode(input,errors)
  39. class IncrementalEncoder(codecs.IncrementalEncoder):
  40. def encode(self, input, final=False):
  41. return quopri_encode(input, self.errors)[0]
  42. class IncrementalDecoder(codecs.IncrementalDecoder):
  43. def decode(self, input, final=False):
  44. return quopri_decode(input, self.errors)[0]
  45. class StreamWriter(Codec, codecs.StreamWriter):
  46. pass
  47. class StreamReader(Codec,codecs.StreamReader):
  48. pass
  49. # encodings module API
  50. def getregentry():
  51. return codecs.CodecInfo(
  52. name='quopri',
  53. encode=quopri_encode,
  54. decode=quopri_decode,
  55. incrementalencoder=IncrementalEncoder,
  56. incrementaldecoder=IncrementalDecoder,
  57. streamwriter=StreamWriter,
  58. streamreader=StreamReader,
  59. _is_text_encoding=False,
  60. )