2014-04-27 00:07:13 +02:00
|
|
|
from itertools import chain
|
2019-09-03 17:14:39 +02:00
|
|
|
from typing import Callable, Iterable, Union
|
2019-08-31 18:21:10 +02:00
|
|
|
|
|
|
|
from httpie.context import Environment
|
2019-09-03 17:14:39 +02:00
|
|
|
from httpie.models import HTTPMessage
|
2019-08-31 18:21:10 +02:00
|
|
|
from httpie.output.processing import Conversion, Formatting
|
2014-04-27 00:07:13 +02:00
|
|
|
|
|
|
|
|
|
|
|
BINARY_SUPPRESSED_NOTICE = (
|
|
|
|
b'\n'
|
|
|
|
b'+-----------------------------------------+\n'
|
|
|
|
b'| NOTE: binary data not shown in terminal |\n'
|
|
|
|
b'+-----------------------------------------+'
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-08-15 17:50:00 +02:00
|
|
|
class DataSuppressedError(Exception):
|
|
|
|
message = None
|
|
|
|
|
|
|
|
|
|
|
|
class BinarySuppressedError(DataSuppressedError):
|
2014-04-27 00:07:13 +02:00
|
|
|
"""An error indicating that the body is binary and won't be written,
|
|
|
|
e.g., for terminal output)."""
|
|
|
|
message = BINARY_SUPPRESSED_NOTICE
|
|
|
|
|
|
|
|
|
2019-08-30 11:32:14 +02:00
|
|
|
class BaseStream:
|
2014-04-27 00:07:13 +02:00
|
|
|
"""Base HTTP message output stream class."""
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
msg: HTTPMessage,
|
2019-09-03 17:14:39 +02:00
|
|
|
with_headers=True,
|
|
|
|
with_body=True,
|
2019-08-31 18:21:10 +02:00
|
|
|
on_body_chunk_downloaded: Callable[[bytes], None] = None
|
|
|
|
):
|
2014-04-27 00:07:13 +02:00
|
|
|
"""
|
|
|
|
:param msg: a :class:`models.HTTPMessage` subclass
|
|
|
|
:param with_headers: if `True`, headers will be included
|
|
|
|
:param with_body: if `True`, body will be included
|
|
|
|
|
|
|
|
"""
|
|
|
|
assert with_headers or with_body
|
|
|
|
self.msg = msg
|
|
|
|
self.with_headers = with_headers
|
|
|
|
self.with_body = with_body
|
|
|
|
self.on_body_chunk_downloaded = on_body_chunk_downloaded
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def get_headers(self) -> bytes:
|
2014-04-27 00:07:13 +02:00
|
|
|
"""Return the headers' bytes."""
|
|
|
|
return self.msg.headers.encode('utf8')
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def iter_body(self) -> Iterable[bytes]:
|
2014-04-27 00:07:13 +02:00
|
|
|
"""Return an iterator over the message body."""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def __iter__(self) -> Iterable[bytes]:
|
2014-04-27 00:07:13 +02:00
|
|
|
"""Return an iterator over `self.msg`."""
|
|
|
|
if self.with_headers:
|
2014-04-28 23:33:30 +02:00
|
|
|
yield self.get_headers()
|
2014-04-27 00:07:13 +02:00
|
|
|
yield b'\r\n\r\n'
|
|
|
|
|
|
|
|
if self.with_body:
|
|
|
|
try:
|
2014-04-28 23:33:30 +02:00
|
|
|
for chunk in self.iter_body():
|
2014-04-27 00:07:13 +02:00
|
|
|
yield chunk
|
|
|
|
if self.on_body_chunk_downloaded:
|
|
|
|
self.on_body_chunk_downloaded(chunk)
|
2020-08-15 17:50:00 +02:00
|
|
|
except DataSuppressedError as e:
|
2014-04-27 00:07:13 +02:00
|
|
|
if self.with_headers:
|
|
|
|
yield b'\n'
|
|
|
|
yield e.message
|
|
|
|
|
|
|
|
|
|
|
|
class RawStream(BaseStream):
|
|
|
|
"""The message is streamed in chunks with no processing."""
|
|
|
|
|
|
|
|
CHUNK_SIZE = 1024 * 100
|
|
|
|
CHUNK_SIZE_BY_LINE = 1
|
|
|
|
|
|
|
|
def __init__(self, chunk_size=CHUNK_SIZE, **kwargs):
|
2019-08-30 11:32:14 +02:00
|
|
|
super().__init__(**kwargs)
|
2014-04-27 00:07:13 +02:00
|
|
|
self.chunk_size = chunk_size
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def iter_body(self) -> Iterable[bytes]:
|
2014-04-27 00:07:13 +02:00
|
|
|
return self.msg.iter_body(self.chunk_size)
|
|
|
|
|
|
|
|
|
|
|
|
class EncodedStream(BaseStream):
|
|
|
|
"""Encoded HTTP message stream.
|
|
|
|
|
|
|
|
The message bytes are converted to an encoding suitable for
|
|
|
|
`self.env.stdout`. Unicode errors are replaced and binary data
|
|
|
|
is suppressed. The body is always streamed by line.
|
|
|
|
|
|
|
|
"""
|
|
|
|
CHUNK_SIZE = 1
|
|
|
|
|
|
|
|
def __init__(self, env=Environment(), **kwargs):
|
2019-08-30 11:32:14 +02:00
|
|
|
super().__init__(**kwargs)
|
2014-04-27 00:07:13 +02:00
|
|
|
if env.stdout_isatty:
|
|
|
|
# Use the encoding supported by the terminal.
|
|
|
|
output_encoding = env.stdout_encoding
|
|
|
|
else:
|
|
|
|
# Preserve the message encoding.
|
|
|
|
output_encoding = self.msg.encoding
|
|
|
|
# Default to utf8 when unsure.
|
|
|
|
self.output_encoding = output_encoding or 'utf8'
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def iter_body(self) -> Iterable[bytes]:
|
2014-04-27 00:07:13 +02:00
|
|
|
for line, lf in self.msg.iter_lines(self.CHUNK_SIZE):
|
|
|
|
if b'\0' in line:
|
|
|
|
raise BinarySuppressedError()
|
|
|
|
yield line.decode(self.msg.encoding) \
|
|
|
|
.encode(self.output_encoding, 'replace') + lf
|
|
|
|
|
|
|
|
|
|
|
|
class PrettyStream(EncodedStream):
|
|
|
|
"""In addition to :class:`EncodedStream` behaviour, this stream applies
|
|
|
|
content processing.
|
|
|
|
|
|
|
|
Useful for long-lived HTTP responses that stream by lines
|
|
|
|
such as the Twitter streaming API.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
CHUNK_SIZE = 1
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def __init__(
|
|
|
|
self, conversion: Conversion,
|
|
|
|
formatting: Formatting,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2019-08-30 11:32:14 +02:00
|
|
|
super().__init__(**kwargs)
|
2014-04-28 23:33:30 +02:00
|
|
|
self.formatting = formatting
|
|
|
|
self.conversion = conversion
|
|
|
|
self.mime = self.msg.content_type.split(';')[0]
|
2014-04-27 00:07:13 +02:00
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def get_headers(self) -> bytes:
|
2014-04-28 23:33:30 +02:00
|
|
|
return self.formatting.format_headers(
|
2014-04-27 00:07:13 +02:00
|
|
|
self.msg.headers).encode(self.output_encoding)
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def iter_body(self) -> Iterable[bytes]:
|
2014-04-28 23:33:30 +02:00
|
|
|
first_chunk = True
|
|
|
|
iter_lines = self.msg.iter_lines(self.CHUNK_SIZE)
|
|
|
|
for line, lf in iter_lines:
|
2014-04-27 00:07:13 +02:00
|
|
|
if b'\0' in line:
|
2014-04-28 23:33:30 +02:00
|
|
|
if first_chunk:
|
|
|
|
converter = self.conversion.get_converter(self.mime)
|
|
|
|
if converter:
|
|
|
|
body = bytearray()
|
|
|
|
# noinspection PyAssignmentToLoopOrWithParameter
|
|
|
|
for line, lf in chain([(line, lf)], iter_lines):
|
|
|
|
body.extend(line)
|
|
|
|
body.extend(lf)
|
|
|
|
self.mime, body = converter.convert(body)
|
|
|
|
assert isinstance(body, str)
|
|
|
|
yield self.process_body(body)
|
|
|
|
return
|
2014-04-27 00:07:13 +02:00
|
|
|
raise BinarySuppressedError()
|
2014-04-28 23:33:30 +02:00
|
|
|
yield self.process_body(line) + lf
|
|
|
|
first_chunk = False
|
2014-04-27 00:07:13 +02:00
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def process_body(self, chunk: Union[str, bytes]) -> bytes:
|
2014-04-28 23:33:30 +02:00
|
|
|
if not isinstance(chunk, str):
|
|
|
|
# Text when a converter has been used,
|
|
|
|
# otherwise it will always be bytes.
|
|
|
|
chunk = chunk.decode(self.msg.encoding, 'replace')
|
|
|
|
chunk = self.formatting.format_body(content=chunk, mime=self.mime)
|
|
|
|
return chunk.encode(self.output_encoding, 'replace')
|
2014-04-27 00:07:13 +02:00
|
|
|
|
|
|
|
|
|
|
|
class BufferedPrettyStream(PrettyStream):
|
|
|
|
"""The same as :class:`PrettyStream` except that the body is fully
|
|
|
|
fetched before it's processed.
|
|
|
|
|
|
|
|
Suitable regular HTTP responses.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
CHUNK_SIZE = 1024 * 10
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def iter_body(self) -> Iterable[bytes]:
|
2014-04-27 00:07:13 +02:00
|
|
|
# Read the whole body before prettifying it,
|
|
|
|
# but bail out immediately if the body is binary.
|
2014-04-28 23:33:30 +02:00
|
|
|
converter = None
|
2014-04-27 00:07:13 +02:00
|
|
|
body = bytearray()
|
2014-04-28 23:33:30 +02:00
|
|
|
|
2014-04-27 00:07:13 +02:00
|
|
|
for chunk in self.msg.iter_body(self.CHUNK_SIZE):
|
2014-04-28 23:33:30 +02:00
|
|
|
if not converter and b'\0' in chunk:
|
|
|
|
converter = self.conversion.get_converter(self.mime)
|
|
|
|
if not converter:
|
|
|
|
raise BinarySuppressedError()
|
2014-04-27 00:07:13 +02:00
|
|
|
body.extend(chunk)
|
|
|
|
|
2014-04-28 23:33:30 +02:00
|
|
|
if converter:
|
|
|
|
self.mime, body = converter.convert(body)
|
|
|
|
|
|
|
|
yield self.process_body(body)
|