source: ftputil/file.py @ 1618:3cb69eca3e41

Last change on this file since 1618:3cb69eca3e41 was 1618:3cb69eca3e41, checked in by Stefan Schwarzer <sschwarzer@…>, 4 years ago
Add `rest` argument to `FTPHost.open` Allow a `rest` argument in `FTPHost.open`. Pass this on to `FTPFile._open` and from there to `self._session.transfercmd`. So far there's no error handling.
File size: 7.5 KB
Line 
1# Copyright (C) 2003-2014, Stefan Schwarzer <sschwarzer@sschwarzer.net>
2# and ftputil contributors (see `doc/contributors.txt`)
3# See the file LICENSE for licensing terms.
4
5"""
6ftputil.file - support for file-like objects on FTP servers
7"""
8
9from __future__ import print_function
10from __future__ import unicode_literals
11
12import io
13
14import ftputil.compat
15import ftputil.error
16import ftputil.socket_file_adapter
17
18
19# This module shouldn't be used by clients of the ftputil library.
20__all__ = []
21
22
23class FTPFile(object):
24    """
25    Represents a file-like object associated with an FTP host. File
26    and socket are closed appropriately if the `close` method is
27    called.
28    """
29
30    # Set timeout in seconds when closing file connections (see ticket #51).
31    _close_timeout = 5
32
33    def __init__(self, host):
34        """Construct the file(-like) object."""
35        self._host = host
36        # pylint: disable=protected-access
37        self._session = host._session
38        # The file is still closed.
39        self.closed = True
40        self._conn = None
41        self._fobj = None
42
43    def _open(self, path, mode, buffering=None, encoding=None, errors=None,
44              newline=None, rest=None):
45        """
46        Open the remote file with given path name and mode.
47
48        Contrary to the `open` builtin, this method returns `None`,
49        instead this file object is modified in-place.
50        """
51        # We use the same arguments as in `io.open`.
52        # pylint: disable=too-many-arguments
53        #
54        # `buffering` argument isn't used at this time.
55        # pylint: disable=unused-argument
56        #
57        # Python 3's `socket.makefile` supports the same interface as
58        # the new `open` builtin, but Python 2 supports only a mode,
59        # but doesn't return an object with the proper interface to
60        # wrap it in `io.TextIOWrapper`.
61        #
62        # Therefore, to make the code work on Python 2 _and_ 3, use
63        # `socket.makefile` to always create a binary file and under
64        # Python 2 wrap it in an adapter class.
65        #
66        # Check mode.
67        if "a" in mode:
68            raise ftputil.error.FTPIOError("append mode not supported")
69        if mode not in ("r", "rb", "rt", "w", "wb", "wt"):
70            raise ftputil.error.FTPIOError("invalid mode '{0}'".format(mode))
71        if "b" in mode and "t" in mode:
72            # Raise a `ValueError` like Python would.
73            raise ValueError("can't have text and binary mode at once")
74        # Convenience variables
75        is_binary_mode = "b" in mode
76        is_read_mode = "r" in mode
77        # Always use binary mode (see above).
78        transfer_type = "I"
79        command = "TYPE {0}".format(transfer_type)
80        with ftputil.error.ftplib_error_to_ftp_io_error:
81            self._session.voidcmd(command)
82        # Make transfer command.
83        command_type = "RETR" if is_read_mode else "STOR"
84        command = "{0} {1}".format(command_type, path)
85        # Force to binary regardless of transfer type (see above).
86        makefile_mode = mode
87        makefile_mode = makefile_mode.replace("t", "")
88        if not "b" in makefile_mode:
89            makefile_mode += "b"
90        # Get connection and file object.
91        with ftputil.error.ftplib_error_to_ftp_io_error:
92            self._conn = self._session.transfercmd(command, rest)
93        # The file object. Under Python 3, this will already be a
94        # `BufferedReader` or `BufferedWriter` object.
95        fobj = self._conn.makefile(makefile_mode)
96        if ftputil.compat.python_version == 2:
97            BufferedIOAdapter = ftputil.socket_file_adapter.BufferedIOAdapter
98            if is_read_mode:
99                fobj = BufferedIOAdapter(fobj, is_readable=True)
100            else:
101                fobj = BufferedIOAdapter(fobj, is_writable=True)
102        if not is_binary_mode:
103            fobj = io.TextIOWrapper(fobj, encoding=encoding,
104                                    errors=errors, newline=newline)
105        self._fobj = fobj
106        # This comes last so that `close` won't try to close `FTPFile`
107        # objects without `_conn` and `_fobj` attributes in case of an
108        # error.
109        self.closed = False
110
111    def __iter__(self):
112        """Return a file iterator."""
113        return self
114
115    def __next__(self):
116        """
117        Return the next line or raise `StopIteration`, if there are
118        no more.
119        """
120        # Apply implicit line ending conversion for text files.
121        line = self.readline()
122        if line:
123            return line
124        else:
125            raise StopIteration
126
127    # Although Python 2.6+ has the `next` builtin function already, it
128    # still requires iterators to have a `next` method.
129    next = __next__
130
131    #
132    # Context manager methods
133    #
134    def __enter__(self):
135        # Return `self`, so it can be accessed as the variable
136        # component of the `with` statement.
137        return self
138
139    def __exit__(self, exc_type, exc_val, exc_tb):
140        # We don't need the `exc_*` arguments here
141        # pylint: disable=unused-argument
142        self.close()
143        # Be explicit
144        return False
145
146    #
147    # Other attributes
148    #
149    def __getattr__(self, attr_name):
150        """
151        Handle requests for attributes unknown to `FTPFile` objects:
152        delegate the requests to the contained file object.
153        """
154        if attr_name in ("encoding flush isatty fileno read readline "
155                         "readlines seek tell truncate name softspace "
156                         "write writelines".split()):
157            return getattr(self._fobj, attr_name)
158        raise AttributeError(
159                "'FTPFile' object has no attribute '{0}'".format(attr_name))
160
161    # TODO: Implement `__dir__`? (See
162    # http://docs.python.org/whatsnew/2.6.html#other-language-changes )
163
164    def close(self):
165        """Close the `FTPFile`."""
166        if self.closed:
167            return
168        # Timeout value to restore, see below.
169        # Statement works only before the try/finally statement,
170        # otherwise Python raises an `UnboundLocalError`.
171        old_timeout = self._session.sock.gettimeout()
172        try:
173            self._fobj.close()
174            self._fobj = None
175            with ftputil.error.ftplib_error_to_ftp_io_error:
176                self._conn.close()
177            # Set a timeout to prevent waiting until server timeout
178            # if we have a server blocking here like in ticket #51.
179            self._session.sock.settimeout(self._close_timeout)
180            try:
181                with ftputil.error.ftplib_error_to_ftp_io_error:
182                    self._session.voidresp()
183            except ftputil.error.FTPIOError as exc:
184                # Ignore some errors, see tickets #51 and #17 at
185                # http://ftputil.sschwarzer.net/trac/ticket/51 and
186                # http://ftputil.sschwarzer.net/trac/ticket/17,
187                # respectively.
188                exc = str(exc)
189                error_code = exc[:3]
190                if exc.splitlines()[0] != "timed out" and \
191                  error_code not in ("150", "426", "450", "451"):
192                    raise
193        finally:
194            # Restore timeout for socket of `FTPFile`'s `ftplib.FTP`
195            # object in case the connection is reused later.
196            self._session.sock.settimeout(old_timeout)
197            # If something went wrong before, the file is probably
198            # defunct and subsequent calls to `close` won't help
199            # either, so we consider the file closed for practical
200            # purposes.
201            self.closed = True
202
203    def __getstate__(self):
204        raise TypeError("cannot serialize FTPFile object")
Note: See TracBrowser for help on using the repository browser.