Skip to content

Commit c7e64ed

Browse files
authored
Fix urlopen() for Python 2 in runqemu.py (#184)
`get_metadata_from_url()` previousl fell back to urllib.urlopen() on HTTPErrors, due to its overly wide `except` (never catch `Exception`!), which leads to unnecessarily long and confusing backtraces. Other places did not have a Python 2 fallback at all. Directly import the `urlopen` function from the respective module to simplify the code. Also drop the unused `urllib.parse` import.
1 parent 77544b4 commit c7e64ed

1 file changed

Lines changed: 8 additions & 14 deletions

File tree

src/tox_lsr/test_scripts/runqemu.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@
1717
import traceback
1818

1919
try:
20-
import urllib.parse
21-
import urllib.request
20+
from urllib.request import urlopen
2221
except ImportError:
23-
import urllib
22+
# Python 2
23+
from urllib import urlopen
2424
from contextlib import contextmanager
2525

2626
import yaml
@@ -149,12 +149,8 @@ def origurl(path):
149149

150150
def get_metadata_from_url(url, metadata_key):
151151
"""Get metadata from given url."""
152-
try:
153-
with urllib.request.urlopen(url) as url_response: # nosec
154-
return url_response.getheader(metadata_key)
155-
except Exception:
156-
with urllib.urlopen(url) as url_response: # nosec
157-
return url_response.getheader(metadata_key)
152+
with urlopen(url) as url_response: # nosec
153+
return url_response.getheader(metadata_key)
158154

159155

160156
def get_inventory_script(inventory):
@@ -164,9 +160,7 @@ def get_inventory_script(inventory):
164160
os.environ["TOX_WORK_DIR"], "standard-inventory-qcow2"
165161
)
166162
try:
167-
with urllib.request.urlopen( # nosec
168-
inventory # nosec
169-
) as url_response: # nosec
163+
with urlopen(inventory) as url_response: # nosec
170164
with open(inventory_tempfile, "wb") as inf:
171165
shutil.copyfileobj(url_response, inf)
172166
os.chmod(inventory_tempfile, 0o777) # nosec
@@ -211,7 +205,7 @@ def fetch_image(url, cache, label):
211205

212206
image_tempfile = tempfile.NamedTemporaryFile(dir=cache, delete=False)
213207
try:
214-
request = urllib.request.urlopen(url) # nosec
208+
request = urlopen(url) # nosec
215209
shutil.copyfileobj(request, image_tempfile)
216210
request.close()
217211
except Exception: # pylint: disable=broad-except
@@ -292,7 +286,7 @@ def centoshtml2image(url, desiredarch):
292286
logging.error("Could not determine CentOS version from %s", url)
293287
return ""
294288

295-
page = urllib.request.urlopen(url) # nosec
289+
page = urlopen(url) # nosec
296290
tree = BeautifulSoup(page.read(), "html.parser")
297291
imagelist = [
298292
td.a["href"]

0 commit comments

Comments
 (0)