base64_codec.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """ Python 'base64_codec' Codec - base64 content transfer encoding
  2. Unlike most of the other codecs which target Unicode, this codec
  3. will return Python string objects for both encode and decode.
  4. Written by Marc-Andre Lemburg (mal@lemburg.com).
  5. """
  6. import codecs, base64
  7. ### Codec APIs
  8. def base64_encode(input,errors='strict'):
  9. """ Encodes the object input and returns a tuple (output
  10. 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. output = base64.encodestring(input)
  17. return (output, len(input))
  18. def base64_decode(input,errors='strict'):
  19. """ Decodes the object input and returns a tuple (output
  20. object, length consumed).
  21. input must be an object which provides the bf_getreadbuf
  22. buffer slot. Python strings, buffer objects and memory
  23. mapped files are examples of objects providing this slot.
  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. output = base64.decodestring(input)
  30. return (output, len(input))
  31. class Codec(codecs.Codec):
  32. def encode(self, input,errors='strict'):
  33. return base64_encode(input,errors)
  34. def decode(self, input,errors='strict'):
  35. return base64_decode(input,errors)
  36. class IncrementalEncoder(codecs.IncrementalEncoder):
  37. def encode(self, input, final=False):
  38. assert self.errors == 'strict'
  39. return base64.encodestring(input)
  40. class IncrementalDecoder(codecs.IncrementalDecoder):
  41. def decode(self, input, final=False):
  42. assert self.errors == 'strict'
  43. return base64.decodestring(input)
  44. class StreamWriter(Codec,codecs.StreamWriter):
  45. pass
  46. class StreamReader(Codec,codecs.StreamReader):
  47. pass
  48. ### encodings module API
  49. def getregentry():
  50. return codecs.CodecInfo(
  51. name='base64',
  52. encode=base64_encode,
  53. decode=base64_decode,
  54. incrementalencoder=IncrementalEncoder,
  55. incrementaldecoder=IncrementalDecoder,
  56. streamwriter=StreamWriter,
  57. streamreader=StreamReader,
  58. _is_text_encoding=False,
  59. )