base64_codec.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """Python 'base64_codec' Codec - base64 content transfer encoding.
  2. This codec de/encodes from bytes to bytes.
  3. Written by Marc-Andre Lemburg (mal@lemburg.com).
  4. """
  5. import codecs
  6. import base64
  7. ### Codec APIs
  8. def base64_encode(input, errors='strict'):
  9. assert errors == 'strict'
  10. return (base64.encodebytes(input), len(input))
  11. def base64_decode(input, errors='strict'):
  12. assert errors == 'strict'
  13. return (base64.decodebytes(input), len(input))
  14. class Codec(codecs.Codec):
  15. def encode(self, input, errors='strict'):
  16. return base64_encode(input, errors)
  17. def decode(self, input, errors='strict'):
  18. return base64_decode(input, errors)
  19. class IncrementalEncoder(codecs.IncrementalEncoder):
  20. def encode(self, input, final=False):
  21. assert self.errors == 'strict'
  22. return base64.encodebytes(input)
  23. class IncrementalDecoder(codecs.IncrementalDecoder):
  24. def decode(self, input, final=False):
  25. assert self.errors == 'strict'
  26. return base64.decodebytes(input)
  27. class StreamWriter(Codec, codecs.StreamWriter):
  28. charbuffertype = bytes
  29. class StreamReader(Codec, codecs.StreamReader):
  30. charbuffertype = bytes
  31. ### encodings module API
  32. def getregentry():
  33. return codecs.CodecInfo(
  34. name='base64',
  35. encode=base64_encode,
  36. decode=base64_decode,
  37. incrementalencoder=IncrementalEncoder,
  38. incrementaldecoder=IncrementalDecoder,
  39. streamwriter=StreamWriter,
  40. streamreader=StreamReader,
  41. _is_text_encoding=False,
  42. )