Skip to content

streamed_file

A file-like object backed by a streaming response.

This module provides :class:StreamedFile, which wraps a streaming iterable response into a seekable, readable file-like interface backed by a temporary file. Data is consumed from the stream in a background thread, allowing reads to proceed as data arrives, with proper blocking semantics for reads ahead of the stream position.

StreamedFile

A seekable, readable file-like object fed by a streaming response.

The stream is consumed by a background daemon thread into a temp file. Reads block until the requested data is available or the stream completes or the file is closed.

Example
from py_misc_utils import streamed_file as sf

# A streaming response, such as requests.get(url, stream=True).iter_content.
resp = iter([b'chunk1', b'chunk2'])

with sf.StreamedFile(resp) as f:
  print(f.read(6))  # b'chunk1'
  print(f.seek(0, 2), f.tell())  # 12
  print(f.read(6))  # b'' at EOF - seek first to re-read
Source code in py_misc_utils/streamed_file.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
class StreamedFile:
  """A seekable, readable file-like object fed by a streaming response.

  The stream is consumed by a background daemon thread into a temp file.
  Reads block until the requested data is available or the stream completes
  or the file is closed.

  Example:
    from py_misc_utils import streamed_file as sf

    # A streaming response, such as requests.get(url, stream=True).iter_content.
    resp = iter([b'chunk1', b'chunk2'])

    with sf.StreamedFile(resp) as f:
      print(f.read(6))  # b'chunk1'
      print(f.seek(0, 2), f.tell())  # 12
      print(f.read(6))  # b'' at EOF - seek first to re-read
  """

  def __init__(self, resp):
    """Initialize the StreamedFile from a streaming response.

    Args:
      resp: An iterable yielding data chunks (e.g. a response stream).
    """
    self._resp = resp
    self._lock = threading.Lock()
    self._cond = threading.Condition(lock=self._lock)

    tmpfile = tempfile.TemporaryFile()  # noqa: SIM115 -- owned by fin_wrap lifecycle
    fw.fin_wrap(self, '_tempfile', tmpfile, finfn=tmpfile.close)

    self._offset = 0
    self._size = 0
    self._completed = False
    self._closed = False
    self._thread = threading.Thread(target=self._stream, daemon=True)
    self._thread.start()

  def _stream(self):
    """Consume the response stream, writing data to the backing temp file."""
    for data in self._resp:
      with self._lock:
        self._tempfile.seek(self._size)
        self._tempfile.write(data)
        self._size += len(data)
        self._cond.notify_all()
        if self._closed:
          break

    with self._lock:
      self._completed = True
      self._cond.notify_all()

  def _wait_completed(self):
    """Block until the stream is fully consumed or the file is closed."""
    with self._lock:
      while not (self._completed or self._closed):
        self._cond.wait()

  def close(self):
    """Close the file, waiting for the streaming thread to finish."""
    with self._lock:
      self._closed = True
      while not self._completed:
        self._cond.wait()

    self._thread.join()

    with self._lock:
      tempfile = self._tempfile
      if tempfile is not None:
        fw.fin_wrap(self, '_tempfile', None)

    if tempfile is not None:
      tempfile.close()

  @property
  def closed(self):
    """Whether the file is closed.

    Returns:
      True if the file has been closed.
    """
    return self._tempfile is None

  def seek(self, pos, whence=os.SEEK_SET):
    """Move the file position indicator.

    Args:
      pos: The position to seek to.
      whence: The reference point (SEEK_SET, SEEK_CUR, or SEEK_END).

    Returns:
      The new absolute offset.
    """
    if whence == os.SEEK_SET:
      offset = pos
    elif whence == os.SEEK_CUR:
      offset = self._offset + pos
    elif whence == os.SEEK_END:
      self._wait_completed()
      offset = self._size + pos
    else:
      alog.xraise(ValueError, f'Invalid seek mode: {whence}')

    if offset > 0:
      if whence != os.SEEK_END:
        self._wait_completed()
      tas.check_le(offset, self._size, msg='Offset out of range')

    tas.check_ge(offset, 0, msg='Offset out of range')

    self._offset = offset

    return offset

  def tell(self):
    """Return the current file position.

    Returns:
      The current offset.
    """
    return self._offset

  def _read(self, offset, size, adj_offset):
    """Read data at offset, blocking until the data is available.

    Args:
      offset: The absolute offset to read from.
      size: The number of bytes to read.
      adj_offset: If True, advance the current position after reading.

    Returns:
      The bytes read.
    """
    while not (self._completed or self._closed or
               (size >= 0 and self._size >= offset + size)):
      self._cond.wait()

    available = self._size - offset
    to_read = min(size, available) if size >= 0 else available
    if not self._closed and to_read > 0:
      self._tempfile.seek(offset)
      data = self._tempfile.read(to_read)
      if adj_offset:
        self._offset += len(data)
    else:
      data = b''

    return data

  def read(self, size=-1):
    """Read up to size bytes from the current position.

    Args:
      size: Number of bytes to read; -1 to read all available.

    Returns:
      The bytes read.
    """
    with self._lock:
      return self._read(self._offset, size, True)

  def read1(self, size=-1):
    """Read up to size bytes (alias for read).

    Args:
      size: Number of bytes to read.

    Returns:
      The bytes read.
    """
    return self.read(size=size)

  def peek(self, size=0):
    """Return bytes from the current position without advancing it.

    Args:
      size: Maximum number of bytes to peek.

    Returns:
      The peeked bytes (may be fewer than requested).
    """
    with self._lock:
      size = min(size, max(1, self._size - self._offset))

      return self._read(self._offset, size, False) if size > 0 else b''

  def pread(self, offset, size):
    """Read bytes at an absolute offset without changing the position.

    Args:
      offset: The absolute offset to read from.
      size: Number of bytes to read.

    Returns:
      The bytes read.
    """
    with self._lock:
      return self._read(offset, size, False)

  def flush(self):
    """No-op; flushing is not applicable to this read-only file."""

  def readable(self):
    """Whether the file is readable.

    Returns:
      True if the file is not closed.
    """
    return not self.closed

  def seekable(self):
    """Whether the file is seekable.

    Returns:
      True if the file is not closed.
    """
    return not self.closed

  def writable(self):
    """Whether the file is writable.

    Returns:
      Always False for StreamedFile.
    """
    return False

  def __enter__(self):
    """Return the file itself when entering a context.

    Returns:
      The StreamedFile instance.
    """
    return self

  def __exit__(self, *exc):
    """Close the file when exiting a context.

    Args:
      *exc: Exception information if an exception occurred.

    Returns:
      False (exceptions are not suppressed).
    """
    self.close()

    return False

closed property

Whether the file is closed.

Returns:

Type Description

True if the file has been closed.

close()

Close the file, waiting for the streaming thread to finish.

Source code in py_misc_utils/streamed_file.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def close(self):
  """Close the file, waiting for the streaming thread to finish."""
  with self._lock:
    self._closed = True
    while not self._completed:
      self._cond.wait()

  self._thread.join()

  with self._lock:
    tempfile = self._tempfile
    if tempfile is not None:
      fw.fin_wrap(self, '_tempfile', None)

  if tempfile is not None:
    tempfile.close()

seek(pos, whence=os.SEEK_SET)

Move the file position indicator.

Parameters:

Name Type Description Default
pos

The position to seek to.

required
whence

The reference point (SEEK_SET, SEEK_CUR, or SEEK_END).

SEEK_SET

Returns:

Type Description

The new absolute offset.

Source code in py_misc_utils/streamed_file.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def seek(self, pos, whence=os.SEEK_SET):
  """Move the file position indicator.

  Args:
    pos: The position to seek to.
    whence: The reference point (SEEK_SET, SEEK_CUR, or SEEK_END).

  Returns:
    The new absolute offset.
  """
  if whence == os.SEEK_SET:
    offset = pos
  elif whence == os.SEEK_CUR:
    offset = self._offset + pos
  elif whence == os.SEEK_END:
    self._wait_completed()
    offset = self._size + pos
  else:
    alog.xraise(ValueError, f'Invalid seek mode: {whence}')

  if offset > 0:
    if whence != os.SEEK_END:
      self._wait_completed()
    tas.check_le(offset, self._size, msg='Offset out of range')

  tas.check_ge(offset, 0, msg='Offset out of range')

  self._offset = offset

  return offset

tell()

Return the current file position.

Returns:

Type Description

The current offset.

Source code in py_misc_utils/streamed_file.py
136
137
138
139
140
141
142
def tell(self):
  """Return the current file position.

  Returns:
    The current offset.
  """
  return self._offset

read(size=-1)

Read up to size bytes from the current position.

Parameters:

Name Type Description Default
size

Number of bytes to read; -1 to read all available.

-1

Returns:

Type Description

The bytes read.

Source code in py_misc_utils/streamed_file.py
171
172
173
174
175
176
177
178
179
180
181
def read(self, size=-1):
  """Read up to size bytes from the current position.

  Args:
    size: Number of bytes to read; -1 to read all available.

  Returns:
    The bytes read.
  """
  with self._lock:
    return self._read(self._offset, size, True)

read1(size=-1)

Read up to size bytes (alias for read).

Parameters:

Name Type Description Default
size

Number of bytes to read.

-1

Returns:

Type Description

The bytes read.

Source code in py_misc_utils/streamed_file.py
183
184
185
186
187
188
189
190
191
192
def read1(self, size=-1):
  """Read up to size bytes (alias for read).

  Args:
    size: Number of bytes to read.

  Returns:
    The bytes read.
  """
  return self.read(size=size)

peek(size=0)

Return bytes from the current position without advancing it.

Parameters:

Name Type Description Default
size

Maximum number of bytes to peek.

0

Returns:

Type Description

The peeked bytes (may be fewer than requested).

Source code in py_misc_utils/streamed_file.py
194
195
196
197
198
199
200
201
202
203
204
205
206
def peek(self, size=0):
  """Return bytes from the current position without advancing it.

  Args:
    size: Maximum number of bytes to peek.

  Returns:
    The peeked bytes (may be fewer than requested).
  """
  with self._lock:
    size = min(size, max(1, self._size - self._offset))

    return self._read(self._offset, size, False) if size > 0 else b''

pread(offset, size)

Read bytes at an absolute offset without changing the position.

Parameters:

Name Type Description Default
offset

The absolute offset to read from.

required
size

Number of bytes to read.

required

Returns:

Type Description

The bytes read.

Source code in py_misc_utils/streamed_file.py
208
209
210
211
212
213
214
215
216
217
218
219
def pread(self, offset, size):
  """Read bytes at an absolute offset without changing the position.

  Args:
    offset: The absolute offset to read from.
    size: Number of bytes to read.

  Returns:
    The bytes read.
  """
  with self._lock:
    return self._read(offset, size, False)

flush()

No-op; flushing is not applicable to this read-only file.

Source code in py_misc_utils/streamed_file.py
221
222
def flush(self):
  """No-op; flushing is not applicable to this read-only file."""

readable()

Whether the file is readable.

Returns:

Type Description

True if the file is not closed.

Source code in py_misc_utils/streamed_file.py
224
225
226
227
228
229
230
def readable(self):
  """Whether the file is readable.

  Returns:
    True if the file is not closed.
  """
  return not self.closed

seekable()

Whether the file is seekable.

Returns:

Type Description

True if the file is not closed.

Source code in py_misc_utils/streamed_file.py
232
233
234
235
236
237
238
def seekable(self):
  """Whether the file is seekable.

  Returns:
    True if the file is not closed.
  """
  return not self.closed

writable()

Whether the file is writable.

Returns:

Type Description

Always False for StreamedFile.

Source code in py_misc_utils/streamed_file.py
240
241
242
243
244
245
246
def writable(self):
  """Whether the file is writable.

  Returns:
    Always False for StreamedFile.
  """
  return False