]>
Commit | Line | Data |
---|---|---|
3257aa99 DM |
1 | """ Python 'base64_codec' Codec - base64 content transfer encoding\r |
2 | \r | |
3 | Unlike most of the other codecs which target Unicode, this codec\r | |
4 | will return Python string objects for both encode and decode.\r | |
5 | \r | |
6 | Written by Marc-Andre Lemburg (mal@lemburg.com).\r | |
7 | \r | |
8 | """\r | |
9 | import codecs, base64\r | |
10 | \r | |
11 | ### Codec APIs\r | |
12 | \r | |
13 | def base64_encode(input,errors='strict'):\r | |
14 | \r | |
15 | """ Encodes the object input and returns a tuple (output\r | |
16 | object, length consumed).\r | |
17 | \r | |
18 | errors defines the error handling to apply. It defaults to\r | |
19 | 'strict' handling which is the only currently supported\r | |
20 | error handling for this codec.\r | |
21 | \r | |
22 | """\r | |
23 | assert errors == 'strict'\r | |
24 | output = base64.encodestring(input)\r | |
25 | return (output, len(input))\r | |
26 | \r | |
27 | def base64_decode(input,errors='strict'):\r | |
28 | \r | |
29 | """ Decodes the object input and returns a tuple (output\r | |
30 | object, length consumed).\r | |
31 | \r | |
32 | input must be an object which provides the bf_getreadbuf\r | |
33 | buffer slot. Python strings, buffer objects and memory\r | |
34 | mapped files are examples of objects providing this slot.\r | |
35 | \r | |
36 | errors defines the error handling to apply. It defaults to\r | |
37 | 'strict' handling which is the only currently supported\r | |
38 | error handling for this codec.\r | |
39 | \r | |
40 | """\r | |
41 | assert errors == 'strict'\r | |
42 | output = base64.decodestring(input)\r | |
43 | return (output, len(input))\r | |
44 | \r | |
45 | class Codec(codecs.Codec):\r | |
46 | \r | |
47 | def encode(self, input,errors='strict'):\r | |
48 | return base64_encode(input,errors)\r | |
49 | def decode(self, input,errors='strict'):\r | |
50 | return base64_decode(input,errors)\r | |
51 | \r | |
52 | class IncrementalEncoder(codecs.IncrementalEncoder):\r | |
53 | def encode(self, input, final=False):\r | |
54 | assert self.errors == 'strict'\r | |
55 | return base64.encodestring(input)\r | |
56 | \r | |
57 | class IncrementalDecoder(codecs.IncrementalDecoder):\r | |
58 | def decode(self, input, final=False):\r | |
59 | assert self.errors == 'strict'\r | |
60 | return base64.decodestring(input)\r | |
61 | \r | |
62 | class StreamWriter(Codec,codecs.StreamWriter):\r | |
63 | pass\r | |
64 | \r | |
65 | class StreamReader(Codec,codecs.StreamReader):\r | |
66 | pass\r | |
67 | \r | |
68 | ### encodings module API\r | |
69 | \r | |
70 | def getregentry():\r | |
71 | return codecs.CodecInfo(\r | |
72 | name='base64',\r | |
73 | encode=base64_encode,\r | |
74 | decode=base64_decode,\r | |
75 | incrementalencoder=IncrementalEncoder,\r | |
76 | incrementaldecoder=IncrementalDecoder,\r | |
77 | streamwriter=StreamWriter,\r | |
78 | streamreader=StreamReader,\r | |
79 | )\r |