source: ftputil/file.py @ 1723:7d731aea5360

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