Skip to content

ftp_fs

FTP FileSystem implementation using ftputil.

This module provides FtpFs, a FileSystem backend accessing remote files over FTP. Connections (FTPHost objects) are pooled through the object cache and file contents are read through the block-cache / writeback machinery since FTP does not support random access reads.

Example
import os
import tempfile
import threading

from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

from py_misc_utils import cached_file as chf
from py_misc_utils.fs import ftp_fs

root = tempfile.mkdtemp()

# Start a local FTP server so the example is runnable as-is.
authorizer = DummyAuthorizer()
authorizer.add_user('user', 'pass', root, perm='elradfmwMT')
handler = FTPHandler
handler.authorizer = authorizer
server = FTPServer(('127.0.0.1', 0), handler)

stop = threading.Event()

def serve():
  while not stop.wait(0.01):
    server.serve_forever(timeout=0.01, blocking=False, handle_exit=False)

threading.Thread(target=serve, daemon=True).start()

host, port = server.address
fs = ftp_fs.FtpFs(cache_iface=chf.CacheInterface(os.path.join(root, 'cache')))

url = f'ftp://user:pass@{host}:{port}'
with fs.open(url + '/hello.txt', mode='wb') as fd:
  fd.write(b'ftp write')

with fs.open(url + '/hello.txt', mode='rb') as fd:
  print(fd.read())

stop.set()
server.close_all()

CacheHandler

Bases: Handler

Object-cache handler creating and keeping alive ftputil.FTPHost objects.

Source code in py_misc_utils/fs/ftp_fs.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
class CacheHandler(objc.Handler):
  """Object-cache handler creating and keeping alive ftputil.FTPHost objects."""

  def __init__(self, *args, **kwargs):
    """Initialize the handler with the FTPHost creation arguments.

    Args:
      *args: Positional arguments forwarded to FTPHost.
      **kwargs: Keyword arguments forwarded to FTPHost.
    """
    super().__init__()
    # Positional and keyword arguments used to create the FTPHost.
    self._args = args
    self._kwargs = kwargs

  def create(self):
    """Create a new FTPHost connection.

    Returns:
      A ftputil.FTPHost connected with the handler arguments.
    """
    host = ftputil.FTPHost(*self._args, **self._kwargs)

    # Explicitly assume server and client clocks to be aligned (the ftputil
    # default): starting from ftputil 6.0.0 the time shift must be set
    # explicitly for stat() to return timestamp data.
    if hasattr(host, 'set_time_shift'):
      host.set_time_shift(0)

    return host

  def is_alive(self, obj):
    """Return True if the connection still responds to keep_alive()."""
    try:
      obj.keep_alive()

      return True
    # Third-party connection probe: any failure means "not alive" - a false
    # negative just drops the pooled connection, which is self-healing.
    except:  # noqa: E722
      return False

  def close(self, obj):
    """Close the FTPHost connection."""
    obj.close()

create()

Create a new FTPHost connection.

Returns:

Type Description

A ftputil.FTPHost connected with the handler arguments.

Source code in py_misc_utils/fs/ftp_fs.py
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def create(self):
  """Create a new FTPHost connection.

  Returns:
    A ftputil.FTPHost connected with the handler arguments.
  """
  host = ftputil.FTPHost(*self._args, **self._kwargs)

  # Explicitly assume server and client clocks to be aligned (the ftputil
  # default): starting from ftputil 6.0.0 the time shift must be set
  # explicitly for stat() to return timestamp data.
  if hasattr(host, 'set_time_shift'):
    host.set_time_shift(0)

  return host

is_alive(obj)

Return True if the connection still responds to keep_alive().

Source code in py_misc_utils/fs/ftp_fs.py
100
101
102
103
104
105
106
107
108
109
def is_alive(self, obj):
  """Return True if the connection still responds to keep_alive()."""
  try:
    obj.keep_alive()

    return True
  # Third-party connection probe: any failure means "not alive" - a false
  # negative just drops the pooled connection, which is self-healing.
  except:  # noqa: E722
    return False

close(obj)

Close the FTPHost connection.

Source code in py_misc_utils/fs/ftp_fs.py
111
112
113
def close(self, obj):
  """Close the FTPHost connection."""
  obj.close()

FtpReader

Reader downloading whole files over an FTP connection.

Source code in py_misc_utils/fs/ftp_fs.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class FtpReader:
  """Reader downloading whole files over an FTP connection."""

  def __init__(self, conn, path):
    """Initialize the reader.

    Args:
      conn: FTPHost connection used for the transfers.
      path: Remote path of the file to read.
    """
    # FTPHost connection used for the transfers and remote file path.
    self._conn = conn
    self._path = path

  @classmethod
  def tag(cls, sres):
    """Build a cache tag from a stat result.

    Args:
      sres: ftputil stat result of the file.

    Returns:
      The cache tag embedding size and modification time.
    """
    return chf.make_tag(size=sres.st_size, mtime=sres.st_mtime)

  def support_blocks(self):
    """Return False since FTP transfers do not support partial reads."""
    return False

  def read_block(self, bpath, offset, size):
    """Copy the whole remote file into a local cache file.

    Args:
      bpath: Local path of the cache file to write the contents to.
      offset: Must be CachedBlockFile.WHOLE_OFFSET since partial reads
        are not supported.
      size: Number of bytes to read; ignored since the whole file is read.

    Returns:
      The number of bytes written into the cache file.
    """
    tas.check_eq(offset,
                 chf.CachedBlockFile.WHOLE_OFFSET,
                 msg=f'Wrong offset for whole content read: {offset}')

    bfd = os.open(bpath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, mode=0o440)
    with open(bfd, mode='wb') as wfd, self._conn.open(self._path, mode='rb') as rfd:
      self._conn.copyfileobj(rfd, wfd)

    return os.path.getsize(bpath)

tag(sres) classmethod

Build a cache tag from a stat result.

Parameters:

Name Type Description Default
sres

ftputil stat result of the file.

required

Returns:

Type Description

The cache tag embedding size and modification time.

Source code in py_misc_utils/fs/ftp_fs.py
130
131
132
133
134
135
136
137
138
139
140
@classmethod
def tag(cls, sres):
  """Build a cache tag from a stat result.

  Args:
    sres: ftputil stat result of the file.

  Returns:
    The cache tag embedding size and modification time.
  """
  return chf.make_tag(size=sres.st_size, mtime=sres.st_mtime)

support_blocks()

Return False since FTP transfers do not support partial reads.

Source code in py_misc_utils/fs/ftp_fs.py
142
143
144
def support_blocks(self):
  """Return False since FTP transfers do not support partial reads."""
  return False

read_block(bpath, offset, size)

Copy the whole remote file into a local cache file.

Parameters:

Name Type Description Default
bpath

Local path of the cache file to write the contents to.

required
offset

Must be CachedBlockFile.WHOLE_OFFSET since partial reads are not supported.

required
size

Number of bytes to read; ignored since the whole file is read.

required

Returns:

Type Description

The number of bytes written into the cache file.

Source code in py_misc_utils/fs/ftp_fs.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def read_block(self, bpath, offset, size):
  """Copy the whole remote file into a local cache file.

  Args:
    bpath: Local path of the cache file to write the contents to.
    offset: Must be CachedBlockFile.WHOLE_OFFSET since partial reads
      are not supported.
    size: Number of bytes to read; ignored since the whole file is read.

  Returns:
    The number of bytes written into the cache file.
  """
  tas.check_eq(offset,
               chf.CachedBlockFile.WHOLE_OFFSET,
               msg=f'Wrong offset for whole content read: {offset}')

  bfd = os.open(bpath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, mode=0o440)
  with open(bfd, mode='wb') as wfd, self._conn.open(self._path, mode='rb') as rfd:
    self._conn.copyfileobj(rfd, wfd)

  return os.path.getsize(bpath)

FtpSession

Bases: FTP

FTP session connecting and logging in upon creation.

Source code in py_misc_utils/fs/ftp_fs.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
class FtpSession(ftplib.FTP):
  """FTP session connecting and logging in upon creation."""

  def __init__(self, host, userid, passwd, port):
    """Connect to an FTP server and authenticate.

    Args:
      host: Server host name or address.
      userid: User name used to login.
      passwd: Password used to login.
      port: TCP port of the FTP server.
    """
    super().__init__()
    self.connect(host, port=port)
    self.login(userid, passwd)

FtpFs

Bases: FsBase

FileSystem implementation for URLs with the ftp:// scheme.

Connections are pooled per (host, port, user) via the object cache and remote contents are staged through the block-cache and writeback-file helpers, so repeated accesses are served from the local cache.

Source code in py_misc_utils/fs/ftp_fs.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
class FtpFs(fsb.FsBase):
  """FileSystem implementation for URLs with the ftp:// scheme.

  Connections are pooled per (host, port, user) via the object cache and
  remote contents are staged through the block-cache and writeback-file
  helpers, so repeated accesses are served from the local cache.
  """

  ID = 'ftp'
  IDS = (ID,)

  def __init__(self, cache_iface=None, **kwargs):
    """Initialize the backend.

    Args:
      cache_iface: Optional cache interface customizing the caching of
        the remote contents.
      **kwargs: Extra keyword arguments forwarded to FsBase.
    """
    super().__init__(cache_iface=cache_iface, **kwargs)

  def _get_connection(self, host, port, user, passwd):
    """Get a pooled FTP connection for the given server credentials.

    Args:
      host: Server host name or address.
      port: TCP port of the FTP server.
      user: Login user name.
      passwd: Login password.

    Returns:
      An ftputil.FTPHost from the object cache, shared per host/port/user.
    """
    handler = CacheHandler(host, user, passwd, port=port, session_factory=FtpSession)
    name = ('FTPFS', host, port, user)

    return objc.cache().get(name, handler)

  def _netloc(self, purl):
    """Return the (host, port) pair identifying the FTP server."""
    return (purl.hostname.lower(), purl.port or 21)

  def _parse_url(self, url):
    """Parse an ftp:// URL and return its pooled connection.

    The server credentials (host, port, user and password) are taken
    from the URL itself: the user defaults to the anonymous user when
    no user is given, while the port defaults to the standard FTP
    port.

    Args:
      url: ftp:// URL to parse.

    Returns:
      A tuple with the FTPHost connection and the parsed URL.
    """
    purl = uparse.urlparse(url)

    host, port = self._netloc(purl)
    user = purl.username or 'anonymous'
    passwd = purl.password or ''

    conn = self._get_connection(host, port, user, passwd)

    return conn, purl

  def _make_reader(self, conn, purl):
    """Create a reader and metadata for the remote file.

    Args:
      conn: FTPHost connection.
      purl: Parsed ftp:// URL.

    Returns:
      A tuple with the FtpReader and the cache Meta describing the file.
    """
    sres = self._stat(conn, purl.path)

    tag = FtpReader.tag(sres)
    meta = chf.Meta(size=sres.st_size, mtime=sres.st_mtime, tag=tag)
    reader = FtpReader(conn, purl.path)

    return reader, meta

  def remove(self, url):
    """Remove a remote file.

    Args:
      url: ftp:// URL of the file to remove.
    """
    conn, purl = self._parse_url(url)
    conn.remove(purl.path)

  def rename(self, src_url, dest_url):
    """Rename a remote file within the same host.

    Args:
      src_url: ftp:// URL of the source file.
      dest_url: ftp:// URL of the destination file.

    Raises:
      RuntimeError: When the source and destination URLs are not on the
        same host.
    """
    src_conn, src_purl = self._parse_url(src_url)
    _, dest_purl = self._parse_url(dest_url)

    src_netloc, dest_netloc = self._netloc(src_purl), self._netloc(dest_purl)

    tas.check_eq(src_netloc, dest_netloc,
                 msg=f'Source and destination URL must be on the same host: ' \
                 f'{src_netloc} vs. {dest_netloc}')

    src_conn.rename(src_purl.path, dest_purl.path)

  def mkdir(self, url, mode=None):
    """Create a remote directory.

    Args:
      url: ftp:// URL of the directory to create.
      mode: Unused, since remote permissions are not supported.
    """
    conn, purl = self._parse_url(url)
    conn.mkdir(purl.path)

  def makedirs(self, url, mode=None, exist_ok=None):
    """Create a remote directory and all its parents.

    Args:
      url: ftp:// URL of the directory to create.
      mode: Unused, since remote permissions are not supported.
      exist_ok: If True, do not raise when the directory already exists
        (default: False).
    """
    conn, purl = self._parse_url(url)

    conn.makedirs(purl.path, exist_ok=exist_ok or False)

  def rmdir(self, url):
    """Remove an empty remote directory.

    Args:
      url: ftp:// URL of the directory to remove.
    """
    conn, purl = self._parse_url(url)
    conn.rmdir(purl.path)

  def rmtree(self, url, ignore_errors=None):
    """Recursively remove a remote directory tree.

    Args:
      url: ftp:// URL of the directory tree to remove.
      ignore_errors: If True, errors raised while removing the tree are
        ignored (default: False).
    """
    conn, purl = self._parse_url(url)

    conn.rmtree(purl.path, ignore_errors=ignore_errors or False)

  def _stat(self, conn, path):
    """Stat a remote path.

    Args:
      conn: FTPHost connection.
      path: Remote path to stat.

    Returns:
      The DirEntry built from the remote stat result.
    """
    sres = conn.stat(path)

    tag = FtpReader.tag(sres)

    return fsb.DirEntry(name=os.path.basename(path),
                        path=path,
                        etag=tag,
                        st_mode=sres.st_mode,
                        st_size=sres.st_size,
                        st_ctime=sres.st_ctime or sres.st_mtime,
                        st_mtime=sres.st_mtime)

  def stat(self, url):
    """Stat a remote path.

    Args:
      url: ftp:// URL to stat.

    Returns:
      The DirEntry of the path.
    """
    conn, purl = self._parse_url(url)

    return self._stat(conn, purl.path)

  def list(self, url):
    """Enumerate the entries of a remote directory.

    Args:
      url: ftp:// URL of the directory to enumerate.

    Yields:
      A DirEntry for every file and subdirectory of the directory.
    """
    conn, purl = self._parse_url(url)

    for name in conn.listdir(purl.path):
      path = os.path.join(purl.path, name)

      yield self._stat(conn, path)

  def open(self, url, mode, **kwargs):
    """Open a URL for reading or writing.

    Read modes are served through the block-cache interface, while write
    modes download the existing contents when truncation is not requested
    and wrap the stream into a WritebackFile uploading on close.

    Args:
      url: ftp:// URL to open.
      mode: Open mode string.
      **kwargs: Extra keyword arguments forwarded to the cache interface.

    Returns:
      A file-like object, wrapped into a TextIOWrapper in text modes.
    """
    conn, purl = self._parse_url(url)

    if self.read_mode(mode):
      reader, meta = self._make_reader(conn, purl)
      cfile = self._cache_iface.open(url, meta, reader, **kwargs)

      return io.TextIOWrapper(cfile) if self.text_mode(mode) else cfile
    else:
      writeback_fn = functools.partial(self._upload_file, url)
      if not self.truncate_mode(mode) and conn.path.exists(purl.path):
        url_file = self._download_file(url)
        self.seek_stream(mode, url_file)
      else:
        # The WritebackFile owns the temp file's lifetime.
        url_file = tempfile.TemporaryFile()  # noqa: SIM115

      wbfile = wbf.WritebackFile(url_file, writeback_fn)

      return io.TextIOWrapper(wbfile) if self.text_mode(mode) else wbfile

  def _upload_file(self, url, stream):
    """Upload the contents of a stream into a remote file.

    Args:
      url: ftp:// URL of the destination file.
      stream: Seekable file-like object with the contents to upload.
    """
    conn, purl = self._parse_url(url)

    stream.seek(0)
    with conn.open(purl.path, mode='wb') as dest_fd:
      conn.copyfileobj(stream, dest_fd)

  def _download_file(self, url):
    """Download a remote file into a temporary local file.

    Args:
      url: ftp:// URL of the file to download.

    Returns:
      A seekable temporary file with the remote contents.
    """
    conn, purl = self._parse_url(url)

    with cm.Wrapper(tempfile.TemporaryFile()) as ftmp:
      with conn.open(purl.path, mode='rb') as src_fd:
        conn.copyfileobj(src_fd, ftmp.v)

      return ftmp.detach()

  def put_file(self, url, data_gen):
    """Write data chunks into a remote file.

    Args:
      url: ftp:// URL of the file to write.
      data_gen: Iterable of bytes chunks to write.
    """
    conn, purl = self._parse_url(url)

    with conn.open(purl.path, mode='wb') as fd:
      for data in data_gen:
        fd.write(data)

  def get_file(self, url):
    """Read the contents of a remote file as chunks.

    Args:
      url: ftp:// URL of the file to read.

    Yields:
      The file contents as bytes chunks.
    """
    conn, purl = self._parse_url(url)

    with conn.open(purl.path, mode='rb') as fd:
      yield from fsu.enum_chunks(fd)

  def as_local(self, url, **kwargs):
    """Return a local file with the contents of a URL.

    Args:
      url: ftp:// URL of the file to access.
      **kwargs: Extra keyword arguments forwarded to the cache interface.

    Returns:
      The path of the local file, downloaded through the cache interface.
    """
    conn, purl = self._parse_url(url)
    reader, meta = self._make_reader(conn, purl)

    return self._cache_iface.as_local(url, meta, reader, **kwargs)

  def link(self, src_url, dest_url):
    """Copy the file, since FTP has no hard link support.

    Args:
      src_url: ftp:// URL of the source file.
      dest_url: ftp:// URL of the destination file.
    """
    # There is not link support in FTP.
    self.copyfile(src_url, dest_url)

  def symlink(self, src_url, dest_url):
    """Copy the file, since FTP has no symbolic link support.

    Args:
      src_url: ftp:// URL of the source file.
      dest_url: ftp:// URL of the destination file.
    """
    self.link(src_url, dest_url)

remove(url)

Remove a remote file.

Parameters:

Name Type Description Default
url

ftp:// URL of the file to remove.

required
Source code in py_misc_utils/fs/ftp_fs.py
272
273
274
275
276
277
278
279
def remove(self, url):
  """Remove a remote file.

  Args:
    url: ftp:// URL of the file to remove.
  """
  conn, purl = self._parse_url(url)
  conn.remove(purl.path)

rename(src_url, dest_url)

Rename a remote file within the same host.

Parameters:

Name Type Description Default
src_url

ftp:// URL of the source file.

required
dest_url

ftp:// URL of the destination file.

required

Raises:

Type Description
RuntimeError

When the source and destination URLs are not on the same host.

Source code in py_misc_utils/fs/ftp_fs.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def rename(self, src_url, dest_url):
  """Rename a remote file within the same host.

  Args:
    src_url: ftp:// URL of the source file.
    dest_url: ftp:// URL of the destination file.

  Raises:
    RuntimeError: When the source and destination URLs are not on the
      same host.
  """
  src_conn, src_purl = self._parse_url(src_url)
  _, dest_purl = self._parse_url(dest_url)

  src_netloc, dest_netloc = self._netloc(src_purl), self._netloc(dest_purl)

  tas.check_eq(src_netloc, dest_netloc,
               msg=f'Source and destination URL must be on the same host: ' \
               f'{src_netloc} vs. {dest_netloc}')

  src_conn.rename(src_purl.path, dest_purl.path)

mkdir(url, mode=None)

Create a remote directory.

Parameters:

Name Type Description Default
url

ftp:// URL of the directory to create.

required
mode

Unused, since remote permissions are not supported.

None
Source code in py_misc_utils/fs/ftp_fs.py
303
304
305
306
307
308
309
310
311
def mkdir(self, url, mode=None):
  """Create a remote directory.

  Args:
    url: ftp:// URL of the directory to create.
    mode: Unused, since remote permissions are not supported.
  """
  conn, purl = self._parse_url(url)
  conn.mkdir(purl.path)

makedirs(url, mode=None, exist_ok=None)

Create a remote directory and all its parents.

Parameters:

Name Type Description Default
url

ftp:// URL of the directory to create.

required
mode

Unused, since remote permissions are not supported.

None
exist_ok

If True, do not raise when the directory already exists (default: False).

None
Source code in py_misc_utils/fs/ftp_fs.py
313
314
315
316
317
318
319
320
321
322
323
324
def makedirs(self, url, mode=None, exist_ok=None):
  """Create a remote directory and all its parents.

  Args:
    url: ftp:// URL of the directory to create.
    mode: Unused, since remote permissions are not supported.
    exist_ok: If True, do not raise when the directory already exists
      (default: False).
  """
  conn, purl = self._parse_url(url)

  conn.makedirs(purl.path, exist_ok=exist_ok or False)

rmdir(url)

Remove an empty remote directory.

Parameters:

Name Type Description Default
url

ftp:// URL of the directory to remove.

required
Source code in py_misc_utils/fs/ftp_fs.py
326
327
328
329
330
331
332
333
def rmdir(self, url):
  """Remove an empty remote directory.

  Args:
    url: ftp:// URL of the directory to remove.
  """
  conn, purl = self._parse_url(url)
  conn.rmdir(purl.path)

rmtree(url, ignore_errors=None)

Recursively remove a remote directory tree.

Parameters:

Name Type Description Default
url

ftp:// URL of the directory tree to remove.

required
ignore_errors

If True, errors raised while removing the tree are ignored (default: False).

None
Source code in py_misc_utils/fs/ftp_fs.py
335
336
337
338
339
340
341
342
343
344
345
def rmtree(self, url, ignore_errors=None):
  """Recursively remove a remote directory tree.

  Args:
    url: ftp:// URL of the directory tree to remove.
    ignore_errors: If True, errors raised while removing the tree are
      ignored (default: False).
  """
  conn, purl = self._parse_url(url)

  conn.rmtree(purl.path, ignore_errors=ignore_errors or False)

stat(url)

Stat a remote path.

Parameters:

Name Type Description Default
url

ftp:// URL to stat.

required

Returns:

Type Description

The DirEntry of the path.

Source code in py_misc_utils/fs/ftp_fs.py
369
370
371
372
373
374
375
376
377
378
379
380
def stat(self, url):
  """Stat a remote path.

  Args:
    url: ftp:// URL to stat.

  Returns:
    The DirEntry of the path.
  """
  conn, purl = self._parse_url(url)

  return self._stat(conn, purl.path)

list(url)

Enumerate the entries of a remote directory.

Parameters:

Name Type Description Default
url

ftp:// URL of the directory to enumerate.

required

Yields:

Type Description

A DirEntry for every file and subdirectory of the directory.

Source code in py_misc_utils/fs/ftp_fs.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def list(self, url):
  """Enumerate the entries of a remote directory.

  Args:
    url: ftp:// URL of the directory to enumerate.

  Yields:
    A DirEntry for every file and subdirectory of the directory.
  """
  conn, purl = self._parse_url(url)

  for name in conn.listdir(purl.path):
    path = os.path.join(purl.path, name)

    yield self._stat(conn, path)

open(url, mode, **kwargs)

Open a URL for reading or writing.

Read modes are served through the block-cache interface, while write modes download the existing contents when truncation is not requested and wrap the stream into a WritebackFile uploading on close.

Parameters:

Name Type Description Default
url

ftp:// URL to open.

required
mode

Open mode string.

required
**kwargs

Extra keyword arguments forwarded to the cache interface.

{}

Returns:

Type Description

A file-like object, wrapped into a TextIOWrapper in text modes.

Source code in py_misc_utils/fs/ftp_fs.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
def open(self, url, mode, **kwargs):
  """Open a URL for reading or writing.

  Read modes are served through the block-cache interface, while write
  modes download the existing contents when truncation is not requested
  and wrap the stream into a WritebackFile uploading on close.

  Args:
    url: ftp:// URL to open.
    mode: Open mode string.
    **kwargs: Extra keyword arguments forwarded to the cache interface.

  Returns:
    A file-like object, wrapped into a TextIOWrapper in text modes.
  """
  conn, purl = self._parse_url(url)

  if self.read_mode(mode):
    reader, meta = self._make_reader(conn, purl)
    cfile = self._cache_iface.open(url, meta, reader, **kwargs)

    return io.TextIOWrapper(cfile) if self.text_mode(mode) else cfile
  else:
    writeback_fn = functools.partial(self._upload_file, url)
    if not self.truncate_mode(mode) and conn.path.exists(purl.path):
      url_file = self._download_file(url)
      self.seek_stream(mode, url_file)
    else:
      # The WritebackFile owns the temp file's lifetime.
      url_file = tempfile.TemporaryFile()  # noqa: SIM115

    wbfile = wbf.WritebackFile(url_file, writeback_fn)

    return io.TextIOWrapper(wbfile) if self.text_mode(mode) else wbfile

put_file(url, data_gen)

Write data chunks into a remote file.

Parameters:

Name Type Description Default
url

ftp:// URL of the file to write.

required
data_gen

Iterable of bytes chunks to write.

required
Source code in py_misc_utils/fs/ftp_fs.py
463
464
465
466
467
468
469
470
471
472
473
474
def put_file(self, url, data_gen):
  """Write data chunks into a remote file.

  Args:
    url: ftp:// URL of the file to write.
    data_gen: Iterable of bytes chunks to write.
  """
  conn, purl = self._parse_url(url)

  with conn.open(purl.path, mode='wb') as fd:
    for data in data_gen:
      fd.write(data)

get_file(url)

Read the contents of a remote file as chunks.

Parameters:

Name Type Description Default
url

ftp:// URL of the file to read.

required

Yields:

Type Description

The file contents as bytes chunks.

Source code in py_misc_utils/fs/ftp_fs.py
476
477
478
479
480
481
482
483
484
485
486
487
488
def get_file(self, url):
  """Read the contents of a remote file as chunks.

  Args:
    url: ftp:// URL of the file to read.

  Yields:
    The file contents as bytes chunks.
  """
  conn, purl = self._parse_url(url)

  with conn.open(purl.path, mode='rb') as fd:
    yield from fsu.enum_chunks(fd)

as_local(url, **kwargs)

Return a local file with the contents of a URL.

Parameters:

Name Type Description Default
url

ftp:// URL of the file to access.

required
**kwargs

Extra keyword arguments forwarded to the cache interface.

{}

Returns:

Type Description

The path of the local file, downloaded through the cache interface.

Source code in py_misc_utils/fs/ftp_fs.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
def as_local(self, url, **kwargs):
  """Return a local file with the contents of a URL.

  Args:
    url: ftp:// URL of the file to access.
    **kwargs: Extra keyword arguments forwarded to the cache interface.

  Returns:
    The path of the local file, downloaded through the cache interface.
  """
  conn, purl = self._parse_url(url)
  reader, meta = self._make_reader(conn, purl)

  return self._cache_iface.as_local(url, meta, reader, **kwargs)

Copy the file, since FTP has no hard link support.

Parameters:

Name Type Description Default
src_url

ftp:// URL of the source file.

required
dest_url

ftp:// URL of the destination file.

required
Source code in py_misc_utils/fs/ftp_fs.py
505
506
507
508
509
510
511
512
513
def link(self, src_url, dest_url):
  """Copy the file, since FTP has no hard link support.

  Args:
    src_url: ftp:// URL of the source file.
    dest_url: ftp:// URL of the destination file.
  """
  # There is not link support in FTP.
  self.copyfile(src_url, dest_url)

Copy the file, since FTP has no symbolic link support.

Parameters:

Name Type Description Default
src_url

ftp:// URL of the source file.

required
dest_url

ftp:// URL of the destination file.

required
Source code in py_misc_utils/fs/ftp_fs.py
515
516
517
518
519
520
521
522
def symlink(self, src_url, dest_url):
  """Copy the file, since FTP has no symbolic link support.

  Args:
    src_url: ftp:// URL of the source file.
    dest_url: ftp:// URL of the destination file.
  """
  self.link(src_url, dest_url)