MCPcopy Create free account
hub / github.com/comaps/comaps / download_file

Function download_file

tools/python/maps_generator/utils/file.py:63–112  ·  view source on GitHub ↗
(url: AnyStr, name: AnyStr, download_if_exists: bool = True)

Source from the content-addressed store, hash-verified

61
62
63def download_file(url: AnyStr, name: AnyStr, download_if_exists: bool = True):
64 logger.info(f"Trying to download {name} from {url}.")
65 if not download_if_exists and os.path.exists(name):
66 logger.info(f"File {name} already exists.")
67 return
68
69 if is_file_uri(url):
70 # url uses 'file://' scheme
71 shutil.copy2(file_uri_to_path(url), name)
72 logger.info(f"File {name} was copied from {url}.")
73 return
74
75 tmp_name = f"{name}__"
76 os.makedirs(os.path.dirname(tmp_name), exist_ok=True)
77 with requests.Session() as session:
78 session.mount("file://", FileAdapter())
79 with open(tmp_name, "wb") as handle:
80 response = session.get(url, stream=True)
81 file_length = None
82 try:
83 file_length = int(response.headers["Content-Length"])
84 except KeyError:
85 logger.warning(
86 f"There is no attribute Content-Length in headers [{url}]: {response.headers}"
87 )
88
89 current = 0
90 max_attempts = 32
91 attempts = max_attempts
92 while attempts:
93 for data in response.iter_content(chunk_size=4096):
94 current += len(data)
95 handle.write(data)
96
97 if file_length is None or file_length == current:
98 break
99
100 logger.warning(
101 f"Download interrupted. Resuming download from {url}: {current}/{file_length}."
102 )
103 headers = {"Range": f"bytes={current}-"}
104 response = session.get(url, headers=headers, stream=True)
105 attempts -= 1
106
107 assert (
108 attempts > 0
109 ), f"Maximum failed resuming download attempts of {max_attempts} is exceeded."
110
111 shutil.move(tmp_name, name)
112 logger.info(f"File {name} was downloaded from {url}.")
113
114
115def is_dir(url) -> bool:

Callers 1

test_booking_dataFunction · 0.90

Calls 5

is_file_uriFunction · 0.85
file_uri_to_pathFunction · 0.85
getMethod · 0.65
writeMethod · 0.45
moveMethod · 0.45

Tested by 1

test_booking_dataFunction · 0.72