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

m.(cdo|tnm).download: Replace requests with urllib #977

Open
wants to merge 2 commits into
base: grass8
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
10 changes: 5 additions & 5 deletions src/misc/m.cdo.download/m.cdo.download.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@

import sys
import os
import requests
import urllib.request
import urllib.error
import json
import grass.script as grass
from grass.script.utils import separator
Expand Down Expand Up @@ -181,11 +182,10 @@ def fetch_once(endpoint, offset, limit):
response = None

for token in tokens:
ret = requests.get(request_url, headers={"token": token})
if ret.status_code != 200:
continue
try:
response = ret.json()
request = urllib.request.Request(request_url, headers={"token": token})
with urllib.request.urlopen(request) as f:
response = json.load(f)
except:
continue
if "message" in response:
Expand Down
47 changes: 26 additions & 21 deletions src/misc/m.tnm.download/m.tnm.download.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@

import sys
import os
import requests
import urllib.request
import urllib.error
import json
import grass.script as grass
from grass.script.utils import separator

Expand Down Expand Up @@ -164,26 +166,32 @@
)


def urlopen(url):
url = url.replace(" ", "%20")
return urllib.request.urlopen(url)
Comment on lines +169 to +171
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is probably encode-decode function which would do this in more general way.

Copy link
Member Author

@HuidaeCho HuidaeCho Nov 7, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found url = urllib.parse.quote(url, safe=":/?=&"), but I liked the above simpler version. Any better suggestion?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was actually surprised that I couldn't find any general URL encode/decode functions that can simply take full URLs.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh BTW, TNM only complained about spaces in URL. That was another reason.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then I don't have a better suggestion. I think a documentation would clarify the existence of the function or a separate function encode_spaces() or encode_X_for_Y() as there seems to be some specificity to this particular case.



def show_datasets(fs):
datasets = query_datasets()
print(f"INDEX{fs}ID{fs}TAG")
print(f"index{fs}id{fs}tag")
for i in range(len(datasets)):
dataset = datasets[i]
print(f"{i}{fs}{dataset['id']}{fs}{dataset['sbDatasetTag']}")


def show_states(fs):
print(f"FIPS{fs}USPS{fs}NAME")
print(f"fips{fs}usps{fs}name")
for state in states:
print(f"{state['fips']}{fs}{state['usps']}{fs}{state['name']}")


def query_datasets():
url = datasets_url
res = requests.get(url)
if res.status_code != 200:
grass.fatal(_("Failed to fetch dataset metadata"))
ret = res.json()
try:
with urlopen(url) as f:
ret = json.load(f)
except urllib.error.HTTPError as e:
grass.fatal(_("Failed to fetch dataset metadata with status code %d") % e.code)

datasets = []
for item in ret:
Expand All @@ -201,13 +209,6 @@ def download_file(item, code, compare_file_size):
filename = url.split("/")[-1]
size = item["sizeInBytes"]
name = code["name"]
res = requests.get(url, stream=True)
if res.status_code != 200:
grass.warning(
_("Failed to download %s with status code %d") % (filename, res.status_code)
)
return

if os.path.exists(filename) and not grass.overwrite():
file_size = os.path.getsize(filename)
if not compare_file_size or file_size == size:
Expand All @@ -218,10 +219,13 @@ def download_file(item, code, compare_file_size):
)

grass.message(_("Downloading %s for %s...") % (filename, name))
with open(filename, "wb") as f:
for chunk in res.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
try:
with urlopen(url) as inf, open(filename, "wb") as outf:
outf.write(inf.read())
except urllib.error.HTTPError as e:
grass.warning(
_("Failed to download %s with status code %d") % (filename, e.code)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.format(filename=..., code=...) is preferred over C-like %s %d. The new code does not have to be outdated just because the surrounding code is.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought C-like formats would be better for cross-language translations, but anyway, we already have Python formats, so not a big deal.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We definitively use .format in new Python code. So far, we weighted the clarity of code and possible order changes in translations over translation reuse. Plus these are not really translated at this point, no? So it is only the code.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wenzeslaus Shouldn't we prefer f-strings (better readability and shorter) in that case when the minimum Python version we support is 3.8?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We didn't adapt the CI yet, but for the main branch, the minimum supported version agreed upon is 3.9. So you are free

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought this was this GRASS repo, not the GRASS addons repo. For addons I don't know, but hope to follow the main grass repo to allow sharing similar maintenance

)


def main():
Expand Down Expand Up @@ -332,8 +336,10 @@ def main():
)
+ date_params
)
res = requests.get(url)
if res.status_code != 200:
try:
with urlopen(url) as f:
ret = json.load(f)
except urllib.error.HTTPError as e:
if total:
grass.fatal(
_("Failed to fetch product metadata for %s (offset %d of %d)")
Expand All @@ -344,7 +350,6 @@ def main():
_("Failed to fetch product metadata for %s (offset %d)")
% (code["name"], offset)
)
ret = res.json()
if not total:
total = ret["total"]
grass.message(_("Number of files to download: %d") % total)
Expand Down
Loading