37
class ResponseFile(object):
38
"""A wrapper around the http socket containing the result of a GET request.
40
Only read() and seek() (forward) are supported.
42
def __init__(self, path, infile):
45
:param path: File url, for error reports.
47
:param infile: File-like socket set at body start.
56
Dummy implementation for consistency with the 'file' API.
59
def read(self, size=-1):
60
"""Read size bytes from the current position in the file.
62
:param size: The number of bytes to read. Leave unspecified or pass
65
data = self._file.read(size)
66
self._pos += len(data)
70
data = self._file.readline()
71
self._pos += len(data)
77
def seek(self, offset, whence=os.SEEK_SET):
78
if whence == os.SEEK_SET:
79
if offset < self._pos:
81
"Can't seek backwards, pos: %s, offset: %s"
82
% (self._pos, offset))
83
to_discard = offset - self._pos
84
elif whence == os.SEEK_CUR:
87
raise AssertionError("Can't seek backwards")
89
# Just discard the unwanted bytes
36
92
# A RangeFile expects the following grammar (simplified to outline the
37
93
# assumptions we rely upon).
43
# whole_file: [content_length_header] data
45
98
# single_range: content_range_header data
47
100
# multiple_range: boundary_header boundary (content_range_header data boundary)+
49
class RangeFile(object):
102
class RangeFile(ResponseFile):
50
103
"""File-like object that allow access to partial available data.
52
105
All accesses should happen sequentially since the acquisition occurs during
73
126
:param path: File url, for error reports.
74
128
:param infile: File-like socket set at body start.
130
super(RangeFile, self).__init__(path, infile)
78
131
self._boundary = None
79
132
# When using multi parts response, this will be set with the headers
80
133
# associated with the range currently read.
298
351
:return: A file-like object that can seek()+read() the
299
352
ranges indicated by the headers.
301
rfile = RangeFile(url, data)
304
size = msg.getheader('content-length', None)
309
rfile.set_range(0, size)
356
rfile = ResponseFile(url, data)
310
357
elif code == 206:
358
rfile = RangeFile(url, data)
311
359
content_type = msg.getheader('content-type', None)
312
360
if content_type is None:
313
361
# When there is no content-type header we treat the response as