Skip to content

Commit 571239a

Browse files
committed
Support chunked transfers in wget
1 parent 25fc43d commit 571239a

File tree

1 file changed

+30
-17
lines changed

1 file changed

+30
-17
lines changed

adafruit_portalbase/network.py

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -333,27 +333,40 @@ def wget(self, url, filename, *, chunk_size=12000, headers=None):
333333

334334
if self._debug:
335335
print(response.headers)
336-
if "content-length" in headers:
337-
content_length = int(headers["content-length"])
338-
else:
339-
raise RuntimeError("Content-Length missing from headers")
340-
remaining = content_length
336+
if "content-length" not in headers and "transfer-encoding" not in headers and headers["transfer-encoding"] == "chunked":
337+
raise RuntimeError("Invalid headers in response")
338+
341339
print("Saving data to ", filename)
342340
stamp = time.monotonic()
343341
with open(filename, "wb") as file:
344-
for i in response.iter_content(min(remaining, chunk_size)): # huge chunks!
345-
self.neo_status(STATUS_DOWNLOADING)
346-
remaining -= len(i)
347-
file.write(i)
348-
if self._debug:
349-
print("Read %d bytes, %d remaining" % (content_length - remaining, remaining))
350-
else:
351-
print(".", end="")
352-
if not remaining:
353-
break
354-
self.neo_status(STATUS_FETCHING)
342+
if "content-length" in headers:
343+
content_length = int(headers["content-length"])
344+
remaining = content_length
345+
for i in response.iter_content(min(remaining, chunk_size)): # huge chunks!
346+
self.neo_status(STATUS_DOWNLOADING)
347+
remaining -= len(i)
348+
file.write(i)
349+
if self._debug:
350+
print("Read %d bytes, %d remaining" % (content_length - remaining, remaining))
351+
else:
352+
print(".", end="")
353+
if not remaining:
354+
break
355+
self.neo_status(STATUS_FETCHING)
356+
response.close()
357+
elif "transfer-encoding" in headers and headers["transfer-encoding"] == "chunked":
358+
content_length = 0
359+
for i in response.iter_content(chunk_size):
360+
self.neo_status(STATUS_DOWNLOADING)
361+
content_length += len(i)
362+
file.write(i)
363+
if self._debug:
364+
print("Read %d bytes, %d total" % (len(i), content_length))
365+
else:
366+
print(".", end="")
367+
self.neo_status(STATUS_FETCHING)
368+
response.close()
355369

356-
response.close()
357370
stamp = time.monotonic() - stamp
358371
print("Created file of %d bytes in %0.1f seconds" % (os.stat(filename)[6], stamp))
359372
self.neo_status(STATUS_OFF)

0 commit comments

Comments
 (0)