| 204 | this attribute will have the same value as the input_codec. |
| 205 | """ |
| 206 | def __init__(self, input_charset=DEFAULT_CHARSET): |
| 207 | # RFC 2046, $4.1.2 says charsets are not case sensitive. We coerce to |
| 208 | # unicode because its .lower() is locale insensitive. If the argument |
| 209 | # is already a unicode, we leave it at that, but ensure that the |
| 210 | # charset is ASCII, as the standard (RFC XXX) requires. |
| 211 | try: |
| 212 | if isinstance(input_charset, str): |
| 213 | input_charset.encode('ascii') |
| 214 | else: |
| 215 | input_charset = str(input_charset, 'ascii') |
| 216 | except UnicodeError: |
| 217 | raise errors.CharsetError(input_charset) |
| 218 | input_charset = input_charset.lower() |
| 219 | # Set the input charset after filtering through the aliases |
| 220 | self.input_charset = ALIASES.get(input_charset, input_charset) |
| 221 | # We can try to guess which encoding and conversion to use by the |
| 222 | # charset_map dictionary. Try that first, but let the user override |
| 223 | # it. |
| 224 | henc, benc, conv = CHARSETS.get(self.input_charset, |
| 225 | (SHORTEST, BASE64, None)) |
| 226 | if not conv: |
| 227 | conv = self.input_charset |
| 228 | # Set the attributes, allowing the arguments to override the default. |
| 229 | self.header_encoding = henc |
| 230 | self.body_encoding = benc |
| 231 | self.output_charset = ALIASES.get(conv, conv) |
| 232 | # Now set the codecs. If one isn't defined for input_charset, |
| 233 | # guess and try a Unicode codec with the same name as input_codec. |
| 234 | self.input_codec = CODEC_MAP.get(self.input_charset, |
| 235 | self.input_charset) |
| 236 | self.output_codec = CODEC_MAP.get(self.output_charset, |
| 237 | self.output_charset) |
| 238 | |
| 239 | def __repr__(self): |
| 240 | return self.input_charset.lower() |