HTTP and HTTPS storage.
| 122 | |
| 123 | |
| 124 | class HTTPStorage(Storage): |
| 125 | """HTTP and HTTPS storage.""" |
| 126 | |
| 127 | def read(self, url): |
| 128 | # TODO @wenmeng.zwm add progress bar if file is too large |
| 129 | r = requests.get(url) |
| 130 | r.raise_for_status() |
| 131 | return r.content |
| 132 | |
| 133 | def read_text(self, url): |
| 134 | r = requests.get(url) |
| 135 | r.raise_for_status() |
| 136 | return r.text |
| 137 | |
| 138 | @contextlib.contextmanager |
| 139 | def as_local_path( |
| 140 | self, filepath: str) -> Generator[Union[str, Path], None, None]: |
| 141 | """Download a file from ``filepath``. |
| 142 | |
| 143 | ``as_local_path`` is decorated by :meth:`contextlib.contextmanager`. It |
| 144 | can be called with ``with`` statement, and when exists from the |
| 145 | ``with`` statement, the temporary path will be released. |
| 146 | |
| 147 | Args: |
| 148 | filepath (str): Download a file from ``filepath``. |
| 149 | |
| 150 | Examples: |
| 151 | >>> storage = HTTPStorage() |
| 152 | >>> # After existing from the ``with`` clause, |
| 153 | >>> # the path will be removed |
| 154 | >>> with storage.get_local_path('http://path/to/file') as path: |
| 155 | ... # do something here |
| 156 | """ |
| 157 | try: |
| 158 | f = tempfile.NamedTemporaryFile(delete=False) |
| 159 | f.write(self.read(filepath)) |
| 160 | f.close() |
| 161 | yield f.name |
| 162 | finally: |
| 163 | os.remove(f.name) |
| 164 | |
| 165 | def write(self, obj: bytes, url: Union[str, Path]) -> None: |
| 166 | raise NotImplementedError('write is not supported by HTTP Storage') |
| 167 | |
| 168 | def write_text(self, |
| 169 | obj: str, |
| 170 | url: Union[str, Path], |
| 171 | encoding: str = 'utf-8') -> None: |
| 172 | raise NotImplementedError( |
| 173 | 'write_text is not supported by HTTP Storage') |
| 174 | |
| 175 | |
| 176 | class OSSStorage(Storage): |
no outgoing calls
searching dependent graphs…