Skip to content

Commit

Permalink
Safe downloads in transfers.py
Browse files Browse the repository at this point in the history
Download remove files to a ".dl" extension so that if the download fails you don't lose the original file. Transfer the files when done.

Also added a "backup" option which leaves a ".bak" file of the original
  • Loading branch information
kfsone committed Dec 17, 2014
1 parent b89a0d1 commit 2d0aa1a
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions transfers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import absolute_import, with_statement, print_function, division, unicode_literals

from pathlib import Path
from tradeexcept import TradeException
from urllib.parse import urlencode
from urllib.request import Request, urlopen
Expand Down Expand Up @@ -47,6 +48,7 @@ def rateVal(bytes, started):
def download(
cmdenv, url, localFile,
headers=None,
backup=False,
):
"""
Fetch data from a URL and save the output
Expand Down Expand Up @@ -89,16 +91,20 @@ def download(
# Fetch four memory pages at a time
chunkSize = 4096 * 4

with open(localFile, "w") as fh:
tmpPath = Path(localFile + ".dl")
actPath = Path(localFile)

with tmpPath.open("w") as fh:
# Use the 'while True' approach so that we always print the
# download status including, especially, the 100% report.
while True:
if not cmdenv.quiet:
print("Download: "
print("{}: "
"{:>{len}n}/{:>{len}n} bytes "
"| {:>10s} "
"| {:>5.2f}% "
.format(
localFile,
fetched, bytes,
rateVal(fetched, started),
(fetched * 100 / bytes),
Expand All @@ -114,5 +120,16 @@ def download(
fetched += len(chunk)
print(chunk.decode(), file=fh, end="")

# Swap the file into place
if backup:
bakPath = Path(localFile + ".bak")
if bakPath.exists():
bakPath.unlink()
if actPath.exists():
actPath.rename(localFile + ".bak")
if actPath.exists():
actPath.unlink()
tmpPath.rename(actPath)

return f.getheaders()

0 comments on commit 2d0aa1a

Please sign in to comment.