use context manager in retrieveURL

This commit is contained in:
Damien Elmes 2020-05-21 10:57:49 +10:00
parent 44ca4b32eb
commit a3ac96443b

View File

@ -803,7 +803,6 @@ to a cloze type first, via Edit>Change Note Type."""
local = False local = False
# fetch it into a temporary folder # fetch it into a temporary folder
self.mw.progress.start(immediate=not local, parent=self.parentWindow) self.mw.progress.start(immediate=not local, parent=self.parentWindow)
response = None
content_type = None content_type = None
error_msg: Optional[str] = None error_msg: Optional[str] = None
try: try:
@ -811,23 +810,23 @@ to a cloze type first, via Edit>Change Note Type."""
req = urllib.request.Request( req = urllib.request.Request(
url, None, {"User-Agent": "Mozilla/5.0 (compatible; Anki)"} url, None, {"User-Agent": "Mozilla/5.0 (compatible; Anki)"}
) )
with urllib.request.urlopen(req) as resp: with urllib.request.urlopen(req) as response:
filecontents = resp.read() filecontents = response.read()
else: else:
client = HttpClient() with HttpClient() as client:
client.timeout = 30 client.timeout = 30
response = client.get(url) with client.get(url) as response:
if response.status_code != 200: if response.status_code != 200:
error_msg = _("Unexpected response code: %s") % response.status_code error_msg = (
return _("Unexpected response code: %s") % response.status_code
filecontents = response.content )
content_type = response.headers.get("content-type") return
filecontents = response.content
content_type = response.headers.get("content-type")
except (urllib.error.URLError, requests.exceptions.RequestException) as e: except (urllib.error.URLError, requests.exceptions.RequestException) as e:
error_msg = _("An error occurred while opening %s") % e error_msg = _("An error occurred while opening %s") % e
return return
finally: finally:
if response:
response.close()
self.mw.progress.finish() self.mw.progress.finish()
if error_msg: if error_msg:
showWarning(error_msg) showWarning(error_msg)