diff --git a/Lib/http/client.py b/Lib/http/client.py --- a/Lib/http/client.py +++ b/Lib/http/client.py @@ -679,6 +679,40 @@ total_bytes += n return total_bytes + def peek(self, n=None): + # Having this enables IOBase.readline() to read more than one + # byte at a time + if self.fp is None or self._method == "HEAD": + return b"" + if self.chunked: + return self._peek_chunked(n) + return self.fp.peek(n) + + def _peek_chunked(self, n): + # Peek at most one chunk into the buffer + if self.chunk_left is not None: + # Peek into the current chunk + if n < 0: + n = self.chunk_left + else: + n = min(n, self.chunk_left) + return self.fp.peek(n) + # Peek into the next chunk + peeked = self.fp.peek(n) + i = peeked.find(b"\n") + if i > 0: + head = peeked[:i] + j = head.find(b";") + if j >= 0: + head = head[:j] # strip chunk-extensions + try: + chunklen = int(head, 16) + except ValueError: + return b"" + i += 1 # advance to chunk start + return peeked[i:chunklen+i] + return b"" + def fileno(self): return self.fp.fileno()