def decode(hdrs, content): """ Takes a multipart boundary encoded string and returns list of (key, value) tuples. """ v = hdrs.get("content-type") if v: v = headers.parse_content_type(v) if not v: return [] try: boundary = v[2]["boundary"].encode("ascii") except (KeyError, UnicodeError): return [] rx = re.compile(br'\bname="([^"]+)"') r = [] for i in content.split(b"--" + boundary): parts = i.splitlines() if len(parts) > 1 and parts[0][0:2] != b"--": match = rx.search(parts[1]) if match: key = match.group(1) value = b"".join(parts[3 + parts[2:].index(b""):]) r.append((key, value)) return r return []
def set_text(self, text): if text is None: self.content = None return enc = self._guess_encoding() try: self.content = encoding.encode(text, enc) except ValueError: # Fall back to UTF-8 and update the content-type header. ct = headers.parse_content_type(self.headers.get("content-type", "")) or ("text", "plain", {}) ct[2]["charset"] = "utf-8" self.headers["content-type"] = headers.assemble_content_type(*ct) enc = "utf8" self.content = text.encode(enc, "replace" if six.PY2 else "surrogateescape")
def set_text(self, text): if text is None: self.content = None return enc = self._guess_encoding() try: self.content = encoding.encode(text, enc) except ValueError: # Fall back to UTF-8 and update the content-type header. ct = headers.parse_content_type( self.headers.get("content-type", "")) or ("text", "plain", {}) ct[2]["charset"] = "utf-8" self.headers["content-type"] = headers.assemble_content_type(*ct) enc = "utf8" self.content = text.encode(enc, "surrogateescape")
def set_text(self, text): if text is None: self.content = None return enc = self._guess_encoding() cached = ( self._text_cache.decoded == text and self._text_cache.encoding == enc and self._text_cache.strict ) if not cached: try: encoded = encoding.encode(text, enc) except ValueError: # Fall back to UTF-8 and update the content-type header. ct = headers.parse_content_type(self.headers.get("content-type", "")) or ("text", "plain", {}) ct[2]["charset"] = "utf-8" self.headers["content-type"] = headers.assemble_content_type(*ct) enc = "utf8" encoded = text.encode(enc, "replace" if six.PY2 else "surrogateescape") self._text_cache = CachedDecode(encoded, enc, True, text) self.content = self._text_cache.encoded
def _get_content_type_charset(self): # type: () -> Optional[str] ct = headers.parse_content_type(self.headers.get("content-type", "")) if ct: return ct[2].get("charset")