Пример #1
0
    def peek(self, size: Optional[int] = None) -> bytes:
        """
        Return bytes from the stream without advancing the position.

        Args:
            size (Optional[int], optional): number of bytes to return. Return default
            chunk size if not provided. Return everything if is -1. Defaults to None.

        Returns:
            bytes: data starting from current stream pos.
        """
        with peek_stream(self) as stream:
            return stream.read(size or self._chunk_size)  # type: ignore
Пример #2
0
    def content_type(self) -> str:
        """
        Resource media type (e.g. application/json, text/plain).

        See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type

        Returns:
            str: string describing the media type of the resource.
        """
        if not self._info.content_type and self.size > 0:
            with peek_stream(self._file, peek=0) as stream:
                content_type = guess_content_type_from_buffer(
                    stream.read(1024))  # type: ignore
            self.set_info(content_type=content_type)
        return self._info.content_type or ""
Пример #3
0
    def save(self,
             data: Union[bytes, bytearray, str] = None,
             close: bool = False) -> "AbcStream":
        """
        Flush and stream everything in the buffer to the actual resource location.

        Does nothing if mode is read-only. Will not close the stream.

        Args:
            data: (Union[bytes, bytearray, str], optional): Write additional data to stream before saving. Defaults to None.
            close (bool, optional): Close stream after saving. Defaults to False.

        Returns:
            [AbcStream]: current stream object.
        """
        if self.closed:
            return self

        if self.is_empty() and not data:
            if close:
                self.close()
            return self

        if "w" in self.mode or "a" in self.mode:
            if data:
                self.write(data)
            self.flush()
            with peek_stream(self._file, peek=0, ignore_closed=True) as stream:
                info = self.write_from_fileobj_(self.uri, stream, self.size,
                                                **self._kwargs)
            self.set_info(info)

        if close:
            self.close()

        return self
Пример #4
0
 def __str__(self):
     with peek_stream(self._file, peek=0) as stream:
         return str(stream.read().decode(self.encoding))
Пример #5
0
 def _iter_bytes_from_buffer(self) -> Iterator[bytes]:
     with peek_stream(self._file, peek=0) as file_:
         read = functools.partial(file_.read, self._chunk_size)
         yield from iter(read, b"")
     self.seek(0)