You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
tempfile.TemporaryFile and httplib incompatibility #59472
In httplib.py, there is this code to try to get the body length:
def_set_content_length(self, body):
# Set the content-length based on the body.thelen=Nonetry:
thelen=str(len(body))
exceptTypeError, te:
# If this is a file-like object, try to# fstat its file descriptortry:
thelen=str(os.fstat(body.fileno()).st_size)
except (AttributeError, OSError):
# Don't send a length if this failedifself.debuglevel>0: print"Cannot stat!!"
However, if the body is a temporary file created by tempfile.TemporaryFile(), the len(body) in the first try throws an AttributeError, not a TypeError, on Windows and so it is not caught and unhappiness ensues. It is fine on Macintosh, and I would presume also on Linux.
Windows behaves different because on the other systems, TemporaryFile() returns an actual file object, and len() on a file throws TypeError. On Windows, TemporaryFile() returns an object that wraps the underlying file, and calling len() on that objects invokes this from tempfile.py (around line 371):
def__getattr__(self, name):
# Attribute lookups are delegated to the underlying file# and cached for non-numeric results# (i.e. methods are cached, closed and friends are not)file=self.__dict__['file']
a=getattr(file, name)
ifnotissubclass(type(a), type(0)):
setattr(self, name, a)
returna
Since the underlying file does not have a __len__ method, the getattr fails and throws AttributeError.
I'm sorry I'm not submitting a patch, but I do not know enough about the design of these two libraries to know whether the correct fix is for httplib to be more broad in the exceptions that cause it to check for a file when len() fails, or if the object returned by TemporaryFile() should be more closely mimicking a true file object and so should be made to throw TypeError when someone tries to use len() on it.
The expected output is "200 OK", and that's what happens on Mac and almost certainly on Linux. On Windows, this is the result:
Traceback (most recent call last):
File "bad.py", line 9, in<module>
c.request('POST', '/', f, {'Content-type' : 'application/octet
File "C:\Python27\lib\httplib.py", line 958, in request
self._send_request(method, url, body, headers)
File "C:\Python27\lib\httplib.py", line 989, in _send_request
self._set_content_length(body)
File "C:\Python27\lib\httplib.py", line 964, in _set_content_len
thelen =str(len(body))
File "C:\Python27\lib\tempfile.py", line 383, in__getattr__
a =getattr(file, name)
AttributeError: 'file'object has no attribute '__len__'
I can confirm that this isn't a problem for 3.x. No-one's listed in the experts list for the httplib module but Senthil appears to be the de factor maintainer so I've added him to the call for his opinion. My feeling would be to do the simplest thing possible and add AttributeError to the list of trapped exceptions.
atsuoishimoto commented on Jul 30, 2012
atsuoishimotomannequin
Mannequin
More actions
patch contains fix and test for 2.7.
With this patch, AttibuteError is captured as Tim sujested.
lemanyk1 commented on May 15, 2013
lemanyk1mannequin
Mannequin
More actions
i think it is not good, len(fd) must raise AttributeError, not TypeError
Catching TypeError on len() looks as an ugly test to check if body is a string. Why not doing the opposite: first to call fileno() and call AttributeError? Or even use hasattr(body, "fileno")?
More general and simple solution is to make tempfile.NamedTemporaryFile new-style class.
Old-style class:
>>> import tempfile
>>> f = tempfile.NamedTemporaryFile()
>>> len(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/serhiy/py/cpython-2.7/Lib/tempfile.py", line 391, in __getattr__
a = getattr(file, name)
AttributeError: 'file' object has no attribute '__len__'
New-style class:
>>> import tempfile
>>> f = tempfile.NamedTemporaryFile()
>>> len(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type '_TemporaryFileWrapper' has no len()
We don't do classic to new style class changes for bug fixes without a compelling reason; we've been bitten by unexpected breakage doing that in the past.
Catching TypeError or AttributeError on len() is a hack, but it is compatible with Python 3 and older code. We could handle this in bpo-23740.
Changing TemporaryFile would solve this issue, but only for TemporaryFile. len() raises AttributeError for other file-like classic classes. So I committed slightly modified Atsuo's patch (extended test as Victor suggested).
As for converting classic classes to new-style classes, see for example bpo-14399. It is not so harmless, as expected, unfortunately. But perhaps it was done multiple times in bug-fix releases.
Activity
tzs commentedon Jul 7, 2012
In httplib.py, there is this code to try to get the body length:
However, if the body is a temporary file created by tempfile.TemporaryFile(), the len(body) in the first try throws an AttributeError, not a TypeError, on Windows and so it is not caught and unhappiness ensues. It is fine on Macintosh, and I would presume also on Linux.
Windows behaves different because on the other systems, TemporaryFile() returns an actual file object, and len() on a file throws TypeError. On Windows, TemporaryFile() returns an object that wraps the underlying file, and calling len() on that objects invokes this from tempfile.py (around line 371):
Since the underlying file does not have a __len__ method, the getattr fails and throws AttributeError.
I'm sorry I'm not submitting a patch, but I do not know enough about the design of these two libraries to know whether the correct fix is for httplib to be more broad in the exceptions that cause it to check for a file when len() fails, or if the object returned by TemporaryFile() should be more closely mimicking a true file object and so should be made to throw TypeError when someone tries to use len() on it.
tjguk commentedon Jul 9, 2012
Could you create a failing test, please, Tim S?
RamchandraApte commentedon Jul 9, 2012
BTW, type(0) should be replaced with int in the code.
tzs commentedon Jul 9, 2012
Here is a program that demonstrates the problem:
The expected output is "200 OK", and that's what happens on Mac and almost certainly on Linux. On Windows, this is the result:
Traceback (most recent call last): File "bad.py", line 9, in <module> c.request('POST', '/', f, {'Content-type' : 'application/octet File "C:\Python27\lib\httplib.py", line 958, in request self._send_request(method, url, body, headers) File "C:\Python27\lib\httplib.py", line 989, in _send_request self._set_content_length(body) File "C:\Python27\lib\httplib.py", line 964, in _set_content_len thelen = str(len(body)) File "C:\Python27\lib\tempfile.py", line 383, in __getattr__ a = getattr(file, name) AttributeError: 'file' object has no attribute '__len__'Changing the lines:
to:
makes it work on Windows.
tjguk commentedon Jul 10, 2012
I can confirm that this isn't a problem for 3.x. No-one's listed in the experts list for the httplib module but Senthil appears to be the de factor maintainer so I've added him to the call for his opinion. My feeling would be to do the simplest thing possible and add AttributeError to the list of trapped exceptions.
atsuoishimoto commentedon Jul 30, 2012
patch contains fix and test for 2.7.
With this patch, AttibuteError is captured as Tim sujested.
lemanyk1 commentedon May 15, 2013
i think it is not good, len(fd) must raise AttributeError, not TypeError
vstinner commentedon Dec 12, 2014
Catching TypeError on len() looks as an ugly test to check if body is a string. Why not doing the opposite: first to call fileno() and call AttributeError? Or even use hasattr(body, "fileno")?
vstinner commentedon Dec 12, 2014
bpo-15267.patch: I would feel more confortable if test_send_tempfile() ensures that the socket contains the file content.
vadmium commentedon Apr 11, 2015
See also bpo-23740, about cleaning up the types for computing Content-Length in 3.5.
serhiy-storchaka commentedon Apr 11, 2015
More general and simple solution is to make tempfile.NamedTemporaryFile new-style class.
Old-style class:
New-style class:
bitdancer commentedon Apr 11, 2015
We don't do classic to new style class changes for bug fixes without a compelling reason; we've been bitten by unexpected breakage doing that in the past.
python-dev commentedon May 16, 2015
New changeset c34513c2a894 by Serhiy Storchaka in branch '2.7':
Issue bpo-15267: HTTPConnection.request() now is compatibile with old-style
https://hg.python.org/cpython/rev/c34513c2a894
serhiy-storchaka commentedon May 16, 2015
Catching TypeError or AttributeError on len() is a hack, but it is compatible with Python 3 and older code. We could handle this in bpo-23740.
Changing TemporaryFile would solve this issue, but only for TemporaryFile. len() raises AttributeError for other file-like classic classes. So I committed slightly modified Atsuo's patch (extended test as Victor suggested).
As for converting classic classes to new-style classes, see for example bpo-14399. It is not so harmless, as expected, unfortunately. But perhaps it was done multiple times in bug-fix releases.