Ignore:
Timestamp:
Aug 3, 2013, 11:41:53 PM (6 years ago)
Author:
Stefan Schwarzer <sschwarzer@…>
Branch:
default
Message:
Wrap the file object returned from `socket.makefile` to satisfy the
requirements of `BufferedReader` and `BufferedWriter` under Python 2.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • ftputil/file.py

    r1321 r1322  
    6363        self._conn = None
    6464        self._fobj = None
     65
     66    def _wrapped_file(self, fobj, is_readable=False, is_writable=False):
     67        """
     68        Return a new file-like object which wraps `fobj` and in
     69        addition has the `readable`, `readinto` and `writable` methods
     70        that `BufferedReader` or `BufferedWriter` require.
     71        """
     72        # I tried to assign the missing methods as bound methods
     73        # directly to `fobj`, but this seemingly isn't possible with
     74        # the file object returned from `socket.makefile`.
     75        class Wrapper(io.RawIOBase):
     76            def __init__(self, fobj):
     77                super(Wrapper, self).__setattr__("_fobj", fobj)
     78            def readable(self):
     79                return is_readable
     80            def writable(self):
     81                return is_writable
     82            def readinto(self, bytearray_):
     83                data = self._fobj.read(len(bytearray_))
     84                bytearray_[:len(data)] = data
     85                return len(data)
     86            def __getattr__(self, name):
     87                return getattr(self._fobj, name)
     88            def __setattr__(self, name, value):
     89                if name == "__IOBase_closed":
     90                    # Delegate to this (`RawIOBase`) instance.
     91                    return super(Wrapper, self).__setattr__(name, value)
     92                else:
     93                    return setattr(self._fobj, name, value)
     94        return Wrapper(fobj)
    6595
    6696    def _open(self, path, mode, buffering=None, encoding=None, errors=None,
     
    109139        fobj = self._conn.makefile(makefile_mode)
    110140        if is_read_mode:
     141            # See implementation of `_wrapped_file`.
     142            fobj = self._wrapped_file(fobj, is_readable=True)
    111143            fobj = io.BufferedReader(fobj)
    112144        else:
     145            # See implementation of `_wrapped_file`.
     146            fobj = self._wrapped_file(fobj, is_writable=True)
    113147            fobj = io.BufferedWriter(fobj)
    114148        if not is_bin_mode:
Note: See TracChangeset for help on using the changeset viewer.