Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Making progress bar optional #103

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions landsatxplore/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ def search(
)
@click.option("--skip", is_flag=True, default=False)
@click.option("--overwrite", is_flag=True, default=False)
@click.option("--show-progress", is_flag=True, default=True)
@click.argument("scenes", type=click.STRING, nargs=-1)
def download(username, password, dataset, output, timeout, skip, overwrite, scenes):
"""Download one or several scenes."""
Expand Down
46 changes: 31 additions & 15 deletions landsatxplore/earthexplorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,17 @@
"landsat_ot_c2_l2": ["5e83d14f30ea90a9", "5e83d14fec7cae84", "632210d4770592cf"]
}


def _get_token(body):
"""Get `csrf_token`."""
csrf = re.findall(r'name="csrf" value="(.+?)"', body)[0]

if not csrf:
raise EarthExplorerError("EE: login failed (csrf token not found).")

return csrf


class EarthExplorer(object):
"""Access Earth Explorer portal."""

Expand All @@ -62,17 +64,18 @@ def login(self, username, password):
"password": password,
"csrf": csrf,
}
rsp = self.session.post(EE_LOGIN_URL, data=payload, allow_redirects=True)
rsp = self.session.post(
EE_LOGIN_URL, data=payload, allow_redirects=True)

if not self.logged_in():
raise EarthExplorerError("EE: login failed.")

def logout(self):
"""Log out from Earth Explorer."""
self.session.get(EE_LOGOUT_URL)

def _download(
self, url, output_dir, timeout, chunk_size=1024, skip=False, overwrite=False
self, url, output_dir, timeout, chunk_size=1024, skip=False, overwrite=False, show_progress=True
):
"""Download remote file given its URL."""
# Check availability of the requested product
Expand Down Expand Up @@ -114,18 +117,24 @@ def _download(
headers=headers,
timeout=timeout,
) as r:
with tqdm(
total=filesize,
unit_scale=True,
unit="B",
unit_divisor=1024,
initial=downloaded_bytes
) as pbar:
if show_progress:
with tqdm(
total=filesize,
unit_scale=True,
unit="B",
unit_divisor=1024,
initial=downloaded_bytes
) as pbar:
with open(local_filename, file_mode) as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
pbar.update(chunk_size)
else:
with open(local_filename, file_mode) as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
pbar.update(chunk_size)
return local_filename

except requests.exceptions.Timeout:
Expand All @@ -140,7 +149,8 @@ def _get_fileinfo(self, download_url, timeout, output_dir):
download_url, stream=True, allow_redirects=True, timeout=timeout
) as r:
file_size = int(r.headers.get("Content-Length"))
local_filename = r.headers["Content-Disposition"].split("=")[-1]
local_filename = r.headers["Content-Disposition"].split(
"=")[-1]
local_filename = local_filename.replace('"', "")
local_filename = os.path.join(output_dir, local_filename)
except requests.exceptions.Timeout:
Expand All @@ -157,6 +167,7 @@ def download(
timeout=300,
skip=False,
overwrite=False,
show_progress=True,
):
"""Download a Landsat scene.

Expand All @@ -172,6 +183,10 @@ def download(
Connection timeout in seconds.
skip : bool, optional
Skip download, only returns the remote filename.
overwrite : bool, optional
Overwrite existing files.
show_progress : bool, optional
Show progress bar for download.

Returns
-------
Expand All @@ -194,12 +209,13 @@ def download(
data_product_id=dataset_id, entity_id=entity_id
)
filename = self._download(
url, output_dir, timeout=timeout, skip=skip, overwrite=overwrite
url, output_dir, timeout=timeout, skip=skip, overwrite=overwrite, show_progress=show_progress
)
break
except EarthExplorerError:
if id_count+1 < id_num:
print('Download failed with dataset id {:d} of {:d}. Re-trying with the next one.'.format(id_count+1, id_num))
print(
'Download failed with dataset id {:d} of {:d}. Re-trying with the next one.'.format(id_count+1, id_num))
pass
else:
print('None of the archived ids succeeded! Update necessary!')
Expand Down