defparse_headers(fp, _class=HTTPMessage): """Parses only RFC2822 headers from a file pointer. email Parser wants to see strings rather than bytes. But a TextIOWrapper around self.rfile would buffer too many bytes from the stream, bytes which we later need to read as bytes. So we read the correct bytes here, as bytes, for email Parser to parse. """ headers = [] whileTrue: line = fp.readline(_MAXLINE + 1) if len(line) > _MAXLINE: raise LineTooLong("header line") headers.append(line) if len(headers) > _MAXHEADERS: raise HTTPException("got more than %d headers" % _MAXHEADERS) if line in (b'\r\n', b'\n', b''): break # 默认 iso-8859-1 编码。避免解析头部错误,用 utf8 编码 # hstring = b''.join(headers).decode('iso-8859-1') hstring = b''.join(headers).decode() return email.parser.Parser(_class=_class).parsestr(hstring)