Retrieve a URL into a temporary location on disk. Requires a URL argument. If a filename is passed, it is used as the temporary file location. The reporthook argument should be a callable that accepts a block number, a read size, and the total file size of the URL target. The d
(url, filename=None, reporthook=None, data=None)
| 192 | |
| 193 | _url_tempfiles = [] |
| 194 | def urlretrieve(url, filename=None, reporthook=None, data=None): |
| 195 | """ |
| 196 | Retrieve a URL into a temporary location on disk. |
| 197 | |
| 198 | Requires a URL argument. If a filename is passed, it is used as |
| 199 | the temporary file location. The reporthook argument should be |
| 200 | a callable that accepts a block number, a read size, and the |
| 201 | total file size of the URL target. The data argument should be |
| 202 | valid URL encoded data. |
| 203 | |
| 204 | If a filename is passed and the URL points to a local resource, |
| 205 | the result is a copy from local file to new file. |
| 206 | |
| 207 | Returns a tuple containing the path to the newly created |
| 208 | data file as well as the resulting HTTPMessage object. |
| 209 | """ |
| 210 | url_type, path = _splittype(url) |
| 211 | |
| 212 | with contextlib.closing(urlopen(url, data)) as fp: |
| 213 | headers = fp.info() |
| 214 | |
| 215 | # Just return the local path and the "headers" for file:// |
| 216 | # URLs. No sense in performing a copy unless requested. |
| 217 | if url_type == "file" and not filename: |
| 218 | return os.path.normpath(path), headers |
| 219 | |
| 220 | # Handle temporary file setup. |
| 221 | if filename: |
| 222 | tfp = open(filename, 'wb') |
| 223 | else: |
| 224 | tfp = tempfile.NamedTemporaryFile(delete=False) |
| 225 | filename = tfp.name |
| 226 | _url_tempfiles.append(filename) |
| 227 | |
| 228 | with tfp: |
| 229 | result = filename, headers |
| 230 | bs = 1024*8 |
| 231 | size = -1 |
| 232 | read = 0 |
| 233 | blocknum = 0 |
| 234 | if "content-length" in headers: |
| 235 | size = int(headers["Content-Length"]) |
| 236 | |
| 237 | if reporthook: |
| 238 | reporthook(blocknum, bs, size) |
| 239 | |
| 240 | while block := fp.read(bs): |
| 241 | read += len(block) |
| 242 | tfp.write(block) |
| 243 | blocknum += 1 |
| 244 | if reporthook: |
| 245 | reporthook(blocknum, bs, size) |
| 246 | |
| 247 | if size >= 0 and read < size: |
| 248 | raise ContentTooShortError( |
| 249 | "retrieval incomplete: got only %i out of %i bytes" |
| 250 | % (read, size), result) |
| 251 |
no test coverage detected
searching dependent graphs…