Skip to content

Commit 49b4b24

Browse files
authored
refactor: migrate from urllib to requests (fixes #1311) (#1569)
* refactor: migrate from urllib to requests * chore(deps): add request in requirements * fix: readlines() in sqlite checker * refactor: `requests.exceptions.HTTPError` -> `requests.ConnectionError` * refactor: requests.ConnectionError -> requests.RequestException
1 parent c0b2ac0 commit 49b4b24

File tree

8 files changed

+34
-37
lines changed

8 files changed

+34
-37
lines changed

cve_bin_tool/available_fix/debian_cve_tracker.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
# Copyright (C) 2021 Intel Corporation
22
# SPDX-License-Identifier: GPL-3.0-or-later
33

4-
from json import dump, load, loads
4+
from json import dump, load
55
from os.path import exists, expanduser, getmtime, join
66
from time import time
77
from typing import Dict
8-
from urllib import request
8+
9+
import requests
910

1011
from cve_bin_tool.cve_scanner import CVEData
1112
from cve_bin_tool.log import LOGGER
@@ -96,8 +97,7 @@ def update_json():
9697
"""Update the Debian CVE JSON file"""
9798

9899
LOGGER.info("Updating Debian CVE JSON file for checking available fixes.")
99-
response = request.urlopen(JSON_URL).read().decode("utf-8") # nosec - static url
100-
response = loads(response)
100+
response = requests.get(JSON_URL).json()
101101
with open(DEB_CVE_JSON_PATH, "w") as debian_json:
102102
dump(response, debian_json, indent=4)
103103
LOGGER.info("Debian CVE JSON file for checking available fixes is updated.")

cve_bin_tool/available_fix/redhat_cve_tracker.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
# Copyright (C) 2021 Intel Corporation
22
# SPDX-License-Identifier: GPL-3.0-or-later
33

4-
from json import loads
54
from re import search, split
65
from typing import Dict
7-
from urllib import error, request
6+
7+
import requests
88

99
from cve_bin_tool.cve_scanner import CVEData
1010
from cve_bin_tool.log import LOGGER
@@ -74,10 +74,9 @@ def cve_info(
7474

7575
def get_data(self, cve_number: str, product: str):
7676
try:
77-
full_query = f"{RH_CVE_API}/{cve_number}.json" # static https url above
78-
response = request.urlopen(full_query).read().decode("utf-8") # nosec
79-
return loads(response)
80-
except error.HTTPError as e:
77+
full_query = f"{RH_CVE_API}/{cve_number}.json"
78+
return requests.get(full_query).json()
79+
except requests.HTTPError as e:
8180
LOGGER.debug(e)
8281

8382
def parse_package_data(self, package_data: str) -> str:

cve_bin_tool/checkers/sqlite.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
1313
"""
1414
import re
15-
import urllib.error as error
16-
import urllib.request as request
15+
16+
import requests
1717

1818
from cve_bin_tool.checkers import Checker
1919
from cve_bin_tool.log import LOGGER
@@ -31,13 +31,11 @@ def get_version_map():
3131
re.compile(r'"*(\d{4}-\d{2}-\d{2} \d+:\d+:\d+ [\w]+)"*'),
3232
]
3333
try:
34-
response = request.urlopen(changeurl) # nosec - static url above
35-
lines = response.readlines()
34+
response = requests.get(changeurl).text
35+
lines = response.splitlines()
3636

3737
last_version = "UNKNOWN"
38-
for line_encoded in lines:
39-
line = line_encoded.decode("UTF-8")
40-
38+
for line in lines:
4139
ver_match = version_pattern.search(line)
4240
if ver_match:
4341
last_version = ver_match.group(1)
@@ -47,7 +45,7 @@ def get_version_map():
4745
version_map.append([last_version, id_match.group(1)])
4846
break
4947

50-
except error.URLError as err:
48+
except requests.RequestException as err:
5149
LOGGER.error("Could not fetch " + changeurl + ", " + str(err))
5250

5351
return version_map

cve_bin_tool/version.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
# Copyright (C) 2021 Intel Corporation
22
# SPDX-License-Identifier: GPL-3.0-or-later
33

4-
import json
54
import textwrap
6-
from urllib import request
75

6+
import requests
87
from packaging import version
98

109
from cve_bin_tool.log import LOGGER
@@ -18,19 +17,18 @@ def check_latest_version():
1817
name: str = "cve-bin-tool"
1918
url: str = f"https://pypi.org/pypi/{name}/json"
2019
try:
21-
with request.urlopen(url) as resp: # nosec - static url above
22-
package_json = json.load(resp)
23-
pypi_version = package_json["info"]["version"]
24-
if pypi_version != VERSION:
20+
package_json = requests.get(url).json()
21+
pypi_version = package_json["info"]["version"]
22+
if pypi_version != VERSION:
23+
LOGGER.info(
24+
f"[bold red]You are running version {VERSION} of {name} but the latest PyPI Version is {pypi_version}.[/]",
25+
extra={"markup": True},
26+
)
27+
if version.parse(VERSION) < version.parse(pypi_version):
2528
LOGGER.info(
26-
f"[bold red]You are running version {VERSION} of {name} but the latest PyPI Version is {pypi_version}.[/]",
29+
"[bold yellow]Alert: We recommend using the latest stable release.[/]",
2730
extra={"markup": True},
2831
)
29-
if version.parse(VERSION) < version.parse(pypi_version):
30-
LOGGER.info(
31-
"[bold yellow]Alert: We recommend using the latest stable release.[/]",
32-
extra={"markup": True},
33-
)
3432
except Exception as error:
3533
LOGGER.warning(
3634
textwrap.dedent(

requirements.csv

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@ srossross_not_in_db,rpmfile
1818
indygreg_not_in_db,zstandard
1919
nir0s_not_in_db,distro
2020
tiran_not_in_db,defusedxml
21-
python_not_in_db,importlib_metadata
21+
python_not_in_db,importlib_metadata
22+
python,requests

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,5 @@ zstandard; python_version >= "3.4"
1717
reportlab
1818
distro
1919
defusedxml
20-
importlib_metadata; python_version < "3.8"
20+
importlib_metadata; python_version < "3.8"
21+
requests

test/test_json.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@
1212
import os
1313
import unittest
1414
from test.utils import LONG_TESTS
15-
from urllib.request import urlopen
1615

1716
import pytest
17+
import requests
1818
from jsonschema import validate
1919
from jsonschema.exceptions import ValidationError
2020

@@ -27,7 +27,7 @@
2727

2828
class TestJSON:
2929
# Download the schema
30-
SCHEMA = json.loads(urlopen(NVD_SCHEMA).read().decode("utf-8"))
30+
SCHEMA = requests.get(NVD_SCHEMA).json()
3131
LOGGER.info("Schema loaded successfully")
3232

3333
@unittest.skipUnless(LONG_TESTS() > 0, "Skipping long tests")

test/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
import os
88
import shutil
99
import tempfile
10-
from urllib.request import urlopen
1110

1211
import pytest
12+
import requests
1313

1414
from cve_bin_tool.async_utils import get_event_loop
1515

@@ -36,9 +36,9 @@ def teardown_class(cls):
3636

3737
def download_file(url, target):
3838
"""helper method to download a file"""
39-
download = urlopen(url)
39+
download = requests.get(url)
4040
with open(target, "wb") as target_file:
41-
target_file.write(download.read())
41+
target_file.write(download.content)
4242
download.close()
4343

4444

0 commit comments

Comments
 (0)