KEMBAR78
gh-98778: Update HTTPError to initialize properly even if fp is None by corona10 · Pull Request #99966 · python/cpython · GitHub
Skip to content
Merged
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
4 changes: 4 additions & 0 deletions Lib/test/test_urllib2.py
Original file line number Diff line number Diff line change
Expand Up @@ -1824,6 +1824,10 @@ def test_HTTPError_interface(self):
expected_errmsg = '<HTTPError %s: %r>' % (err.code, err.msg)
self.assertEqual(repr(err), expected_errmsg)

def test_gh_98778(self):
x = urllib.error.HTTPError("url", 405, "METHOD NOT ALLOWED", None, None)
self.assertEqual(getattr(x, "__notes__", ()), ())

def test_parse_proxy(self):
parse_proxy_test_cases = [
('proxy.example.com',
Expand Down
11 changes: 4 additions & 7 deletions Lib/urllib/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
an application may want to handle an exception like a regular
response.
"""

import io
import urllib.response

__all__ = ['URLError', 'HTTPError', 'ContentTooShortError']
Expand Down Expand Up @@ -42,12 +42,9 @@ def __init__(self, url, code, msg, hdrs, fp):
self.hdrs = hdrs
self.fp = fp
self.filename = url
# The addinfourl classes depend on fp being a valid file
# object. In some cases, the HTTPError may not have a valid
# file object. If this happens, the simplest workaround is to
# not initialize the base classes.
if fp is not None:
self.__super_init(fp, hdrs, url, code)
if fp is None:
fp = io.StringIO()
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't this be BytesIO?

from urllib.request import urlopen
from urllib.error import HTTPError
try:
    urlopen('http://asadsad.sd')
except HTTPError as exception:
    content = exception.fp.read()
    print(type(content))
<class 'bytes'>

self.__super_init(fp, hdrs, url, code)

def __str__(self):
return 'HTTP Error %s: %s' % (self.code, self.msg)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Update :exc:`~urllib.error.HTTPError` to be initialized properly, even if
the ``fp`` is ``None``. Patch by Dong-hee Na.