Use wget to download files instead of urllib; reducing code duplication and fixing a bug

This commit is contained in:
Daniel Markstedt 2021-10-26 21:50:00 -07:00
parent e5f58bb967
commit 46698c7b05
2 changed files with 16 additions and 25 deletions

View File

@ -188,29 +188,23 @@ def download_file_to_iso(scsi_id, url):
Takes int scsi_id and str url
Returns dict with boolean status and str msg
"""
import urllib.request
import urllib.error as error
import time
from time import time
from subprocess import run
server_info = get_server_info()
file_name = url.split("/")[-1]
tmp_ts = int(time.time())
tmp_ts = int(time())
tmp_dir = "/tmp/" + str(tmp_ts) + "/"
os.mkdir(tmp_dir)
tmp_full_path = tmp_dir + file_name
iso_filename = f"{server_info['image_dir']}/{file_name}.iso"
try:
urllib.request.urlretrieve(url, tmp_full_path)
except (error.URLError, error.HTTPError, error.ContentTooShortError, FileNotFoundError) as e:
logging.error(str(e))
return {"status": False, "msg": str(e)}
except:
return {"status": False, "msg": "Unknown error occurred."}
wget_proc = download_to_dir(url, tmp_dir)
if wget_proc["status"] == False:
return {"status": False, "msg": wget_proc["msg"]}
# iso_filename = make_cd(tmp_full_path, None, None) # not working yet
iso_proc = run(
["genisoimage", "-hfs", "-o", iso_filename, tmp_full_path], capture_output=True
)
@ -225,20 +219,17 @@ def download_to_dir(url, save_dir):
Takes str url, str save_dir
Returns dict with boolean status and str msg
"""
import urllib.request
import urllib.error as error
from subprocess import run
file_name = url.split("/")[-1]
full_path = f"{save_dir}/{file_name}"
wget_proc = run(
["wget", url, "-P", save_dir], capture_output=True
)
if wget_proc.returncode != 0:
stderr = wget_proc.stderr.decode("utf-8")
logging.warning(f"Downloading failed: {stderr}")
return {"status": False, "msg": stderr}
try:
urllib.request.urlretrieve(url, full_path)
return {"status": True, "msg": "Downloaded the URL"}
except (error.URLError, error.HTTPError, error.ContentTooShortError, FileNotFoundError) as e:
logging.error(str(e))
return {"status": False, "msg": str(e)}
except:
return {"status": False, "msg": "Unknown error occurred."}
return {"status": True, "msg": f"{url} downloaded to {save_dir}"}
def write_config(file_name):

View File

@ -502,7 +502,7 @@ def download_to_iso():
flash(process["msg"], "error")
return redirect(url_for("index"))
process_attach = attach_image(scsi_id, type="SCCD", image=process["file_name"])
process_attach = attach_image(scsi_id, device_type="SCCD", image=process["file_name"])
if process_attach["status"] == True:
flash(f"Attached to SCSI ID {scsi_id}")
return redirect(url_for("index"))