Provide thread-safe memory buffer-like random read access to a file-like object via an efficient item getter interface. Args: fp (:class:`io.BufferedIOBase`/:class:`io.RawIOBase`/binary-file-like): A file-like object that supports seek and readinto operations.
| 117 | |
| 118 | |
| 119 | class GettableFile(GettableBase): |
| 120 | """Provide thread-safe memory buffer-like random read access to a file-like |
| 121 | object via an efficient item getter interface. |
| 122 | |
| 123 | Args: |
| 124 | fp (:class:`io.BufferedIOBase`/:class:`io.RawIOBase`/binary-file-like): |
| 125 | A file-like object that supports seek and readinto operations. |
| 126 | Thread-safety of these operations is not assumed. |
| 127 | |
| 128 | strict (bool, default=True): |
| 129 | Require file-like object to be a :class:`io.BufferedIOBase` or |
| 130 | :class:`io.RawIOBase` instance. |
| 131 | |
| 132 | Note: |
| 133 | :class:`.GettableFile` implements :class:`.Gettable` interface over a |
| 134 | file-like object that supports buffered binary read access. |
| 135 | |
| 136 | Example: |
| 137 | Access overlapping segments of a file from multiple threads:: |
| 138 | |
| 139 | with open('/path/to/file', 'rb') as fp: # binary mode, read access |
| 140 | gf = GettableFile(fp): |
| 141 | |
| 142 | # in thread 1: |
| 143 | seg = gf[0:10] |
| 144 | |
| 145 | # in thread 2: |
| 146 | seg = gf[5:15] |
| 147 | |
| 148 | """ |
| 149 | |
| 150 | def __init__(self, fp, strict=True): |
| 151 | if strict: |
| 152 | valid = lambda f: ( |
| 153 | isinstance(f, (io.BufferedIOBase, io.RawIOBase)) |
| 154 | and f.seekable() and f.readable()) |
| 155 | else: |
| 156 | valid = lambda f: all([ |
| 157 | hasattr(f, 'readinto'), hasattr(f, 'seek'), hasattr(f, 'tell')]) |
| 158 | |
| 159 | if not valid(fp): |
| 160 | raise TypeError("expected file-like, seekable, readable object") |
| 161 | |
| 162 | # store file size, assuming it won't change |
| 163 | self._size = fp.seek(0, os.SEEK_END) |
| 164 | if self._size is None: |
| 165 | # handle non-python3 and/or non-standard file seek() impl. |
| 166 | # (like tempfile.SpooledTemporaryFile) |
| 167 | # note: not thread-safe! |
| 168 | self._size = fp.tell() |
| 169 | |
| 170 | self._fp = fp |
| 171 | |
| 172 | # multiple threads will be accessing the underlying file |
| 173 | self._lock = threading.RLock() |
| 174 | |
| 175 | def __len__(self): |
| 176 | return self._size |
no outgoing calls