Skip to content

Commit 226263c

Browse files
committed
Better error handling for "pre_process_and_fetch_license_dict"
Signed-off-by: Chin Yeung Li <[email protected]>
1 parent aca15df commit 226263c

File tree

1 file changed

+24
-18
lines changed

1 file changed

+24
-18
lines changed

src/attributecode/model.py

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
import json
2828
import os
2929
import posixpath
30-
from requests import get
30+
import requests
3131
import traceback
3232
from itertools import zip_longest
3333

@@ -2069,24 +2069,30 @@ def pre_process_and_fetch_license_dict(abouts, from_check=False, api_url=None, a
20692069
license_url = url + lic_key + '.json'
20702070
license_text_url = url + lic_key + '.LICENSE'
20712071
try:
2072-
json_url_content = get(license_url).text
2073-
# We don't want to actually get the license
2074-
# information from the check utility
2075-
if from_check:
2076-
continue
2077-
data = json.loads(json_url_content)
2078-
license_name = data['short_name']
2079-
license_text = get(license_text_url).text
2080-
license_filename = data['key'] + '.LICENSE'
2081-
lic_url = url + license_filename
2082-
spdx_license_key = data['spdx_license_key']
2083-
except:
2084-
if afp:
2085-
msg = afp + u" : Invalid 'license': " + lic_key
2072+
response = requests.head(license_url)
2073+
if response.status_code < 400:
2074+
json_url_content = requests.get(
2075+
license_url).text
2076+
# We don't want to actually get the license
2077+
# information from the check utility
2078+
if from_check:
2079+
continue
2080+
data = json.loads(json_url_content)
2081+
license_name = data['short_name']
2082+
license_text = get(license_text_url).text
2083+
license_filename = data['key'] + '.LICENSE'
2084+
lic_url = url + license_filename
2085+
spdx_license_key = data['spdx_license_key']
20862086
else:
2087-
msg = u"Invalid 'license': " + lic_key
2087+
if afp:
2088+
msg = afp + u" : Invalid 'license': " + lic_key
2089+
else:
2090+
msg = u"Invalid 'license': " + lic_key
2091+
errors.append(Error(ERROR, msg))
2092+
continue
2093+
except requests.exceptions.RequestException as e:
2094+
msg = f"An error occurred while trying to access the URL: {e}"
20882095
errors.append(Error(ERROR, msg))
2089-
continue
20902096
if not from_check:
20912097
detail_list.append(license_name)
20922098
detail_list.append(license_filename)
@@ -2148,7 +2154,7 @@ def detect_special_char(expression):
21482154

21492155
def valid_api_url(api_url):
21502156
try:
2151-
response = get(api_url)
2157+
response = requests.get(api_url)
21522158
# The 403 error code is expected if the api_url is pointing to DJE as no
21532159
# API key is provided. The 200 status code represent connection success
21542160
# to scancode's LicenseDB. All other exception yield to invalid api_url

0 commit comments

Comments
 (0)