Skip to content

s3_fs

S3 FileSystem implementation using boto3.

This module provides S3Fs, a FileSystem backend for s3:// URLs backed by the boto3 S3 client. Credentials are resolved from a user entry of the ~/.aws.conf configuration file or from the AWS_* environment variables, and clients are pooled per user through the object cache. Reads go through the block-cache machinery (S3 supports ranged reads) while writes are staged locally and uploaded on close.

CacheHandler

Bases: Handler

Object-cache handler creating pooled boto3 S3 clients.

Source code in py_misc_utils/fs/s3_fs.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
class CacheHandler(objc.Handler):
  """Object-cache handler creating pooled boto3 S3 clients."""

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

    Args:
      *args: Positional arguments forwarded to _create_client(), such as
        the resolved credentials.
      **kwargs: Keyword arguments forwarded to _create_client().
    """
    super().__init__()
    # Credentials used to create the S3 client.
    self._args = args
    self._kwargs = kwargs

  def create(self):
    """Create a new S3 client.

    Returns:
      A boto3 S3 client configured with the handler credentials.
    """
    return _create_client(*self._args, **self._kwargs)

create()

Create a new S3 client.

Returns:

Type Description

A boto3 S3 client configured with the handler credentials.

Source code in py_misc_utils/fs/s3_fs.py
395
396
397
398
399
400
401
def create(self):
  """Create a new S3 client.

  Returns:
    A boto3 S3 client configured with the handler credentials.
  """
  return _create_client(*self._args, **self._kwargs)

S3Reader

Reader fetching data from S3 using ranged reads.

Source code in py_misc_utils/fs/s3_fs.py
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
class S3Reader:
  """Reader fetching data from S3 using ranged reads."""

  def __init__(self, client, bucket, path, sres):
    """Initialize the reader.

    Args:
      client: boto3 S3 client used for the reads.
      bucket: Name of the bucket holding the object.
      path: Key of the object to read.
      sres: DirEntry of the object.
    """
    # S3 client, bucket and object key of the file to read and its stat
    # result.
    self._client = client
    self._bucket = bucket
    self._path = path
    self._sres = sres

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

    Args:
      sres: DirEntry of the object, as returned by _stat().

    Returns:
      The object ETag, or a tag built from size and modification time.
    """
    return sres.etag or chf.make_tag(size=sres.st_size, mtime=sres.st_mtime)

  def support_blocks(self):
    """Return True since S3 supports ranged reads."""
    return True

  def read_block(self, bpath, offset, size):
    """Read data into a local cache file.

    Args:
      bpath: Local path of the cache file to write the contents to.
      offset: Offset in the object where reading starts; WHOLE_OFFSET
        streams the whole object.
      size: Number of bytes to read.

    Returns:
      The number of bytes written into the cache file.
    """
    if offset != chf.CachedBlockFile.WHOLE_OFFSET:
      size = min(size, self._sres.st_size - offset)

      stream, _ = _read_object(self._client,
                               self._bucket,
                               self._path,
                               rdrange=(offset, offset + size))

      with osfd.OsFd(bpath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, mode=0o440) as wfd:
        for data in stream.iter_chunks():
          os.write(wfd, data)
    else:
      stream, _ = _read_object(self._client, self._bucket, self._path)

      with osfd.OsFd(bpath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, mode=0o440) as wfd:
        for data in stream.iter_chunks():
          os.write(wfd, data)

    return os.path.getsize(bpath)

tag(sres) classmethod

Build a cache tag from an S3 stat result.

Parameters:

Name Type Description Default
sres

DirEntry of the object, as returned by _stat().

required

Returns:

Type Description

The object ETag, or a tag built from size and modification time.

Source code in py_misc_utils/fs/s3_fs.py
423
424
425
426
427
428
429
430
431
432
433
@classmethod
def tag(cls, sres):
  """Build a cache tag from an S3 stat result.

  Args:
    sres: DirEntry of the object, as returned by _stat().

  Returns:
    The object ETag, or a tag built from size and modification time.
  """
  return sres.etag or chf.make_tag(size=sres.st_size, mtime=sres.st_mtime)

support_blocks()

Return True since S3 supports ranged reads.

Source code in py_misc_utils/fs/s3_fs.py
435
436
437
def support_blocks(self):
  """Return True since S3 supports ranged reads."""
  return True

read_block(bpath, offset, size)

Read data into a local cache file.

Parameters:

Name Type Description Default
bpath

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

required
offset

Offset in the object where reading starts; WHOLE_OFFSET streams the whole object.

required
size

Number of bytes to read.

required

Returns:

Type Description

The number of bytes written into the cache file.

Source code in py_misc_utils/fs/s3_fs.py
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
def read_block(self, bpath, offset, size):
  """Read data into a local cache file.

  Args:
    bpath: Local path of the cache file to write the contents to.
    offset: Offset in the object where reading starts; WHOLE_OFFSET
      streams the whole object.
    size: Number of bytes to read.

  Returns:
    The number of bytes written into the cache file.
  """
  if offset != chf.CachedBlockFile.WHOLE_OFFSET:
    size = min(size, self._sres.st_size - offset)

    stream, _ = _read_object(self._client,
                             self._bucket,
                             self._path,
                             rdrange=(offset, offset + size))

    with osfd.OsFd(bpath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, mode=0o440) as wfd:
      for data in stream.iter_chunks():
        os.write(wfd, data)
  else:
    stream, _ = _read_object(self._client, self._bucket, self._path)

    with osfd.OsFd(bpath, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, mode=0o440) as wfd:
      for data in stream.iter_chunks():
        os.write(wfd, data)

  return os.path.getsize(bpath)

S3Fs

Bases: FsBase

FileSystem implementation for s3:// URLs.

S3 clients are pooled per resolved credentials through the object cache, while reads and writes go through the block-cache and writeback-file machinery. Since S3 objects are flat, listings fold paths below the query prefix into pseudo-directory entries.

The credentials are resolved from the user name of the URL - when present - looked up as a user entry of the ~/.aws.conf configuration file (see _get_credentials); URLs without a user fall back to the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN environment variables.

See py_misc_utils.fs for the shared backend contract.

Example
from py_misc_utils import cached_file as chf
from py_misc_utils.fs import s3_fs as sf

iface = chf.CacheInterface('/tmp/gfs-cache')
# s3://prod@my-bucket resolves the 'prod' user of ~/.aws.conf.
fs = sf.S3Fs(cache_dir='/tmp/gfs-cache', cache_iface=iface)

with fs.open('s3://my-bucket/data/file.bin', mode='rb') as f:
  header = f.read(512)
Source code in py_misc_utils/fs/s3_fs.py
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
class S3Fs(fsb.FsBase):
  """FileSystem implementation for s3:// URLs.

  S3 clients are pooled per resolved credentials through the object cache,
  while reads and writes go through the block-cache and writeback-file
  machinery. Since S3 objects are flat, listings fold paths below the
  query prefix into pseudo-directory entries.

  The credentials are resolved from the user name of the URL - when
  present - looked up as a user entry of the ~/.aws.conf configuration
  file (see _get_credentials); URLs without a user fall back to the
  AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN
  environment variables.

  See py_misc_utils.fs for the shared backend contract.

  Example:
    from py_misc_utils import cached_file as chf
    from py_misc_utils.fs import s3_fs as sf

    iface = chf.CacheInterface('/tmp/gfs-cache')
    # s3://prod@my-bucket resolves the 'prod' user of ~/.aws.conf.
    fs = sf.S3Fs(cache_dir='/tmp/gfs-cache', cache_iface=iface)

    with fs.open('s3://my-bucket/data/file.bin', mode='rb') as f:
      header = f.read(512)
  """

  ID = 's3'
  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_client(self, purl):
    """Get a pooled S3 client.

    Args:
      purl: Parsed s3:// URL whose user name selects the credentials, as
        per _get_credentials().

    Returns:
      The S3 client from the object cache, shared per user name.
    """
    creds = _get_credentials(user=purl.username)
    handler = CacheHandler(creds)
    name = ('S3FS', purl.username or '$local')

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

  def _parse_url(self, url):
    """Parse an s3:// URL and return its S3 client.

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

    Returns:
      A tuple with the S3 client and the parsed URL with the leading
      slash of the path removed.
    """
    purl = uparse.urlparse(url)
    purl = purl._replace(path=purl.path.lstrip('/'))
    client = self._get_client(purl)

    return client, purl

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

    Args:
      client: boto3 S3 client.
      purl: Parsed s3:// URL.

    Returns:
      A tuple with the S3Reader and the cache Meta describing the object.
    """
    sres = _stat_object(client, purl.hostname, purl.path)

    tag = S3Reader.tag(sres)
    meta = chf.Meta(size=sres.st_size, mtime=sres.st_mtime, tag=tag)
    reader = S3Reader(client, purl.hostname, purl.path, sres)

    return reader, meta

  def _copy(self, src_url, dest_url):
    """Server-side copy an object within the same bucket.

    Args:
      src_url: s3:// URL of the source object.
      dest_url: s3:// URL of the destination object.
    """
    src_client, src_purl = self._parse_url(src_url)
    _, dest_purl = self._parse_url(dest_url)

    tas.check_eq(src_purl.hostname, dest_purl.hostname,
                 msg=f'Source and destination URL must be on the same bucket: ' \
                 f'{src_url} vs. {dest_url}')

    src_client.copy_object(
        Bucket=src_purl.hostname,
        CopySource=dict(Bucket=src_purl.hostname, Key=src_purl.path),
        Key=dest_purl.path,
    )

  def remove(self, url):
    """Remove an object.

    Args:
      url: s3:// URL of the object to remove.
    """
    client, purl = self._parse_url(url)
    client.delete_object(Bucket=purl.hostname, Key=purl.path)

  def rename(self, src_url, dest_url):
    """Rename an object with a copy followed by a delete.

    Args:
      src_url: s3:// URL of the source object.
      dest_url: s3:// URL of the destination object.
    """
    self._copy(src_url, dest_url)

    src_client, src_purl = self._parse_url(src_url)
    src_client.delete_object(Bucket=src_purl.hostname, Key=src_purl.path)

  def mkdir(self, url, mode=None):
    """No-op since S3 has no real directories."""

  def makedirs(self, url, mode=None, exist_ok=None):
    """No-op since S3 has no real directories."""

  def rmdir(self, url):
    """No-op since S3 has no real directories."""

  def rmtree(self, url, ignore_errors=None):
    """Recursively remove all the objects under a URL.

    Args:
      url: s3:// URL of the prefix to remove.
      ignore_errors: When True errors raised while removing the objects
        are logged instead of propagating.
    """
    client, purl = self._parse_url(url)

    _rmtree(client, purl.hostname, purl.path, ignore_errors=ignore_errors)

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

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

    Returns:
      The DirEntry of the path.

    Raises:
      FileNotFoundError: If the path does not exist.
    """
    client, purl = self._parse_url(url)

    dentry = _stat(client, purl.hostname, purl.path)
    tas.check_is_not_none(dentry,
                          exception=FileNotFoundError,
                          msg=f'Not found: {purl.hostname}:{purl.path}')

    return dentry

  def list(self, url):
    """List the entries under a URL.

    Args:
      url: s3:// URL of the prefix to enumerate.

    Returns:
      A list of DirEntry objects for the entries under the prefix.
    """
    client, purl = self._parse_url(url)

    return _list(client, purl.hostname, purl.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: s3:// 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.
    """
    client, purl = self._parse_url(url)

    if self.read_mode(mode):
      reader, meta = self._make_reader(client, 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 self.exists(url):
        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):
    """Rewind a stream and upload its contents to the given URL.

    Args:
      url: Destination s3:// URL of the upload.
      stream: Seekable file-like object with the contents to upload.
    """
    stream.seek(0)
    self.put_file(url, stream)

  def _download_file(self, url):
    """Download the contents of a URL into a temporary file.

    Args:
      url: s3:// URL to download.

    Returns:
      A seekable temporary file with the downloaded contents.
    """
    with cm.Wrapper(tempfile.TemporaryFile()) as ftmp:
      for data in self.get_file(url):
        ftmp.v.write(data)

      return ftmp.detach()

  def put_file(self, url, stream):
    """Upload data to a URL.

    Args:
      url: Destination s3:// URL of the upload.
      stream: Data to upload, as a stream or an iterable of chunks, as
        per _write_object().
    """
    client, purl = self._parse_url(url)

    _write_object(client, purl.hostname, purl.path, stream)

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

    Args:
      url: s3:// URL to read.

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

    stream, _ = _read_object(client, purl.hostname, purl.path)

    yield from stream.iter_chunks()

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

    Args:
      url: s3:// 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.
    """
    client, purl = self._parse_url(url)
    reader, meta = self._make_reader(client, purl)

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

  def link(self, src_url, dest_url):
    """Copy an object, since S3 has no hard links.

    Args:
      src_url: s3:// URL of the source object.
      dest_url: s3:// URL of the destination object.
    """
    self._copy(src_url, dest_url)

  def symlink(self, src_url, dest_url):
    """Copy an object, since S3 has no symbolic links.

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

remove(url)

Remove an object.

Parameters:

Name Type Description Default
url

s3:// URL of the object to remove.

required
Source code in py_misc_utils/fs/s3_fs.py
583
584
585
586
587
588
589
590
def remove(self, url):
  """Remove an object.

  Args:
    url: s3:// URL of the object to remove.
  """
  client, purl = self._parse_url(url)
  client.delete_object(Bucket=purl.hostname, Key=purl.path)

rename(src_url, dest_url)

Rename an object with a copy followed by a delete.

Parameters:

Name Type Description Default
src_url

s3:// URL of the source object.

required
dest_url

s3:// URL of the destination object.

required
Source code in py_misc_utils/fs/s3_fs.py
592
593
594
595
596
597
598
599
600
601
602
def rename(self, src_url, dest_url):
  """Rename an object with a copy followed by a delete.

  Args:
    src_url: s3:// URL of the source object.
    dest_url: s3:// URL of the destination object.
  """
  self._copy(src_url, dest_url)

  src_client, src_purl = self._parse_url(src_url)
  src_client.delete_object(Bucket=src_purl.hostname, Key=src_purl.path)

mkdir(url, mode=None)

No-op since S3 has no real directories.

Source code in py_misc_utils/fs/s3_fs.py
604
605
def mkdir(self, url, mode=None):
  """No-op since S3 has no real directories."""

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

No-op since S3 has no real directories.

Source code in py_misc_utils/fs/s3_fs.py
607
608
def makedirs(self, url, mode=None, exist_ok=None):
  """No-op since S3 has no real directories."""

rmdir(url)

No-op since S3 has no real directories.

Source code in py_misc_utils/fs/s3_fs.py
610
611
def rmdir(self, url):
  """No-op since S3 has no real directories."""

rmtree(url, ignore_errors=None)

Recursively remove all the objects under a URL.

Parameters:

Name Type Description Default
url

s3:// URL of the prefix to remove.

required
ignore_errors

When True errors raised while removing the objects are logged instead of propagating.

None
Source code in py_misc_utils/fs/s3_fs.py
613
614
615
616
617
618
619
620
621
622
623
def rmtree(self, url, ignore_errors=None):
  """Recursively remove all the objects under a URL.

  Args:
    url: s3:// URL of the prefix to remove.
    ignore_errors: When True errors raised while removing the objects
      are logged instead of propagating.
  """
  client, purl = self._parse_url(url)

  _rmtree(client, purl.hostname, purl.path, ignore_errors=ignore_errors)

stat(url)

Stat a path.

Parameters:

Name Type Description Default
url

s3:// URL to stat.

required

Returns:

Type Description

The DirEntry of the path.

Raises:

Type Description
FileNotFoundError

If the path does not exist.

Source code in py_misc_utils/fs/s3_fs.py
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
def stat(self, url):
  """Stat a path.

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

  Returns:
    The DirEntry of the path.

  Raises:
    FileNotFoundError: If the path does not exist.
  """
  client, purl = self._parse_url(url)

  dentry = _stat(client, purl.hostname, purl.path)
  tas.check_is_not_none(dentry,
                        exception=FileNotFoundError,
                        msg=f'Not found: {purl.hostname}:{purl.path}')

  return dentry

list(url)

List the entries under a URL.

Parameters:

Name Type Description Default
url

s3:// URL of the prefix to enumerate.

required

Returns:

Type Description

A list of DirEntry objects for the entries under the prefix.

Source code in py_misc_utils/fs/s3_fs.py
646
647
648
649
650
651
652
653
654
655
656
657
def list(self, url):
  """List the entries under a URL.

  Args:
    url: s3:// URL of the prefix to enumerate.

  Returns:
    A list of DirEntry objects for the entries under the prefix.
  """
  client, purl = self._parse_url(url)

  return _list(client, purl.hostname, purl.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

s3:// 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/s3_fs.py
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
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: s3:// 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.
  """
  client, purl = self._parse_url(url)

  if self.read_mode(mode):
    reader, meta = self._make_reader(client, 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 self.exists(url):
      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, stream)

Upload data to a URL.

Parameters:

Name Type Description Default
url

Destination s3:// URL of the upload.

required
stream

Data to upload, as a stream or an iterable of chunks, as per _write_object().

required
Source code in py_misc_utils/fs/s3_fs.py
719
720
721
722
723
724
725
726
727
728
729
def put_file(self, url, stream):
  """Upload data to a URL.

  Args:
    url: Destination s3:// URL of the upload.
    stream: Data to upload, as a stream or an iterable of chunks, as
      per _write_object().
  """
  client, purl = self._parse_url(url)

  _write_object(client, purl.hostname, purl.path, stream)

get_file(url)

Read the contents of a URL as chunks.

Parameters:

Name Type Description Default
url

s3:// URL to read.

required

Yields:

Type Description

The file contents as bytes chunks.

Source code in py_misc_utils/fs/s3_fs.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
def get_file(self, url):
  """Read the contents of a URL as chunks.

  Args:
    url: s3:// URL to read.

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

  stream, _ = _read_object(client, purl.hostname, purl.path)

  yield from stream.iter_chunks()

as_local(url, **kwargs)

Return a local file with the contents of a URL.

Parameters:

Name Type Description Default
url

s3:// 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/s3_fs.py
746
747
748
749
750
751
752
753
754
755
756
757
758
759
def as_local(self, url, **kwargs):
  """Return a local file with the contents of a URL.

  Args:
    url: s3:// 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.
  """
  client, purl = self._parse_url(url)
  reader, meta = self._make_reader(client, purl)

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

Copy an object, since S3 has no hard links.

Parameters:

Name Type Description Default
src_url

s3:// URL of the source object.

required
dest_url

s3:// URL of the destination object.

required
Source code in py_misc_utils/fs/s3_fs.py
761
762
763
764
765
766
767
768
def link(self, src_url, dest_url):
  """Copy an object, since S3 has no hard links.

  Args:
    src_url: s3:// URL of the source object.
    dest_url: s3:// URL of the destination object.
  """
  self._copy(src_url, dest_url)

Copy an object, since S3 has no symbolic links.

Parameters:

Name Type Description Default
src_url

s3:// URL of the source object.

required
dest_url

s3:// URL of the destination object.

required
Source code in py_misc_utils/fs/s3_fs.py
770
771
772
773
774
775
776
777
def symlink(self, src_url, dest_url):
  """Copy an object, since S3 has no symbolic links.

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