Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the
(self, charset)
| 349 | self.set_charset(charset) |
| 350 | |
| 351 | def set_charset(self, charset): |
| 352 | """Set the charset of the payload to a given character set. |
| 353 | |
| 354 | charset can be a Charset instance, a string naming a character set, or |
| 355 | None. If it is a string it will be converted to a Charset instance. |
| 356 | If charset is None, the charset parameter will be removed from the |
| 357 | Content-Type field. Anything else will generate a TypeError. |
| 358 | |
| 359 | The message will be assumed to be of type text/* encoded with |
| 360 | charset.input_charset. It will be converted to charset.output_charset |
| 361 | and encoded properly, if needed, when generating the plain text |
| 362 | representation of the message. MIME headers (MIME-Version, |
| 363 | Content-Type, Content-Transfer-Encoding) will be added as needed. |
| 364 | """ |
| 365 | if charset is None: |
| 366 | self.del_param('charset') |
| 367 | self._charset = None |
| 368 | return |
| 369 | if not isinstance(charset, Charset): |
| 370 | charset = Charset(charset) |
| 371 | self._charset = charset |
| 372 | if 'MIME-Version' not in self: |
| 373 | self.add_header('MIME-Version', '1.0') |
| 374 | if 'Content-Type' not in self: |
| 375 | self.add_header('Content-Type', 'text/plain', |
| 376 | charset=charset.get_output_charset()) |
| 377 | else: |
| 378 | self.set_param('charset', charset.get_output_charset()) |
| 379 | if charset != charset.get_output_charset(): |
| 380 | self._payload = charset.body_encode(self._payload) |
| 381 | if 'Content-Transfer-Encoding' not in self: |
| 382 | cte = charset.get_body_encoding() |
| 383 | try: |
| 384 | cte(self) |
| 385 | except TypeError: |
| 386 | # This 'if' is for backward compatibility, it allows unicode |
| 387 | # through even though that won't work correctly if the |
| 388 | # message is serialized. |
| 389 | payload = self._payload |
| 390 | if payload: |
| 391 | try: |
| 392 | payload = payload.encode('ascii', 'surrogateescape') |
| 393 | except UnicodeError: |
| 394 | payload = payload.encode(charset.output_charset) |
| 395 | self._payload = charset.body_encode(payload) |
| 396 | self.add_header('Content-Transfer-Encoding', cte) |
| 397 | |
| 398 | def get_charset(self): |
| 399 | """Return the Charset instance associated with the message's payload. |
no test coverage detected