Skip to content

tempfile.TemporaryFile and httplib incompatibility #59472

Closed

Description

@tzs
mannequin
BPO 15267
Nosy @atsuoishimoto, @orsenthil, @vstinner, @tjguk, @bitdancer, @vadmium, @serhiy-storchaka, @demianbrecht
Files
  • issue15267.patch
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = 'https://github.com/serhiy-storchaka'
    closed_at = <Date 2015-05-16.16:07:44.809>
    created_at = <Date 2012-07-07.00:24:34.769>
    labels = ['type-bug', 'OS-windows']
    title = 'tempfile.TemporaryFile and httplib incompatibility'
    updated_at = <Date 2015-05-16.16:07:44.808>
    user = 'https://bugs.python.org/tzs'

    bugs.python.org fields:

    activity = <Date 2015-05-16.16:07:44.808>
    actor = 'serhiy.storchaka'
    assignee = 'serhiy.storchaka'
    closed = True
    closed_date = <Date 2015-05-16.16:07:44.809>
    closer = 'serhiy.storchaka'
    components = ['Windows']
    creation = <Date 2012-07-07.00:24:34.769>
    creator = 'tzs'
    dependencies = []
    files = ['26595']
    hgrepos = []
    issue_num = 15267
    keywords = ['patch', 'needs review']
    message_count = 14.0
    messages = ['164764', '165074', '165076', '165093', '165183', '166867', '189285', '232533', '232534', '240469', '240470', '240481', '243327', '243328']
    nosy_count = 12.0
    nosy_names = ['ishimoto', 'orsenthil', 'vstinner', 'tim.golden', 'r.david.murray', 'python-dev', 'Ramchandra Apte', 'martin.panter', 'serhiy.storchaka', 'tzs', 'lemanyk1', 'demian.brecht']
    pr_nums = []
    priority = 'normal'
    resolution = 'fixed'
    stage = 'resolved'
    status = 'closed'
    superseder = None
    type = 'behavior'
    url = 'https://bugs.python.org/issue15267'
    versions = ['Python 2.7']

    Activity

    1. tzs commented on Jul 7, 2012

      tzsmannequin
      MannequinAuthor

      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 = None
              try:
                  thelen = str(len(body))
              except TypeError, te:
                  # If this is a file-like object, try to
                  # fstat its file descriptor
                  try:
                      thelen = str(os.fstat(body.fileno()).st_size)
                  except (AttributeError, OSError):
                      # Don't send a length if this failed
                      if self.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)
              if not issubclass(type(a), type(0)):
                  setattr(self, name, a)
              return a

      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.

    2. tjguk commented on Jul 9, 2012

      @tjguk
      Member

      Could you create a failing test, please, Tim S?

    3. RamchandraApte commented on Jul 9, 2012

      RamchandraAptemannequin
      Mannequin

      BTW, type(0) should be replaced with int in the code.

    4. tzs commented on Jul 9, 2012

      tzsmannequin
      MannequinAuthor

      Here is a program that demonstrates the problem:

          import httplib
          import tempfile
      
          f = tempfile.TemporaryFile()
          f.write("Hello, Temporary File!")
          f.seek(0)
      
          c = httplib.HTTPConnection('bugs.python.org')
          c.request('POST', '/', f, {'Content-type' : 'application/octet-stream'})
      
          r = c.getresponse()
          print r.status, r.reason

      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:

          f = tempfile.TemporaryFile()
          f.write("Hello, Temporary File!")
          f.seek(0)

      to:

          f = open("temp.file", "w+")
          f.write("Hello, Less Temporary File!")
          f.seek(0)

      makes it work on Windows.

    5. tjguk commented on Jul 10, 2012

      @tjguk
      Member

      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.

    6. atsuoishimoto commented on Jul 30, 2012

      atsuoishimotomannequin
      Mannequin

      patch contains fix and test for 2.7.
      With this patch, AttibuteError is captured as Tim sujested.

    7. lemanyk1 commented on May 15, 2013

      lemanyk1mannequin
      Mannequin

      i think it is not good, len(fd) must raise AttributeError, not TypeError

    8. vstinner commented on Dec 12, 2014

      @vstinner
      Member

      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")?

    9. vstinner commented on Dec 12, 2014

      @vstinner
      Member

      bpo-15267.patch: I would feel more confortable if test_send_tempfile() ensures that the socket contains the file content.

    10. vadmium commented on Apr 11, 2015

      @vadmium
      Member

      See also bpo-23740, about cleaning up the types for computing Content-Length in 3.5.

    11. serhiy-storchaka commented on Apr 11, 2015

      @serhiy-storchaka
      Member

      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()
    12. bitdancer commented on Apr 11, 2015

      @bitdancer
      Member

      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.

    13. python-dev commented on May 16, 2015

      python-devmannequin
      Mannequin

      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

    14. serhiy-storchaka commented on May 16, 2015

      @serhiy-storchaka
      Member

      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.

    15. transferred this issue fromon Apr 10, 2022
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Labels

    OS-windowstype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions