r"""wget(url, save=None, timeout=5) -> str Downloads a file via HTTP/HTTPS. Arguments: url (str): URL to download save (str or bool): Name to save as. Any truthy value will auto-generate a name based on the URL. timeout (int): Timeout, in seconds Example
(url, save=None, timeout=5, **kwargs)
| 13 | log = getLogger(__name__) |
| 14 | |
| 15 | def wget(url, save=None, timeout=5, **kwargs): |
| 16 | r"""wget(url, save=None, timeout=5) -> str |
| 17 | |
| 18 | Downloads a file via HTTP/HTTPS. |
| 19 | |
| 20 | Arguments: |
| 21 | url (str): URL to download |
| 22 | save (str or bool): Name to save as. Any truthy value |
| 23 | will auto-generate a name based on the URL. |
| 24 | timeout (int): Timeout, in seconds |
| 25 | |
| 26 | Example: |
| 27 | |
| 28 | >>> url = 'https://httpbingo.org/robots.txt' |
| 29 | >>> result = wget(url, timeout=60) |
| 30 | >>> result |
| 31 | b'User-agent: *\nDisallow: /deny\n' |
| 32 | |
| 33 | >>> filename = tempfile.mktemp() |
| 34 | >>> result2 = wget(url, filename, timeout=60) |
| 35 | >>> result == open(filename, 'rb').read() |
| 36 | True |
| 37 | """ |
| 38 | import requests |
| 39 | |
| 40 | with log.progress("Downloading %r" % url, rate=0.1) as w: |
| 41 | w.status("Making request...") |
| 42 | |
| 43 | response = requests.get(url, stream=True, timeout=timeout, **kwargs) |
| 44 | |
| 45 | if not response.ok: |
| 46 | w.failure("Got code %s" % response.status_code) |
| 47 | return |
| 48 | |
| 49 | total_size = int(response.headers.get('content-length',0)) |
| 50 | |
| 51 | w.status('0 / %s' % size(total_size)) |
| 52 | |
| 53 | # Find out the next largest size we can represent as |
| 54 | chunk_size = 1 |
| 55 | while chunk_size < (total_size/10): |
| 56 | chunk_size *= 1000 |
| 57 | |
| 58 | # Count chunks as they're received |
| 59 | buf = Buffer() |
| 60 | |
| 61 | # Loop until we have all of the data |
| 62 | for chunk in response.iter_content(chunk_size = 2**10): |
| 63 | buf.add(chunk) |
| 64 | if total_size: |
| 65 | w.status('%s / %s' % (size(buf.size), size(total_size))) |
| 66 | else: |
| 67 | w.status('%s' % size(buf.size)) |
| 68 | |
| 69 | total_data = buf.get() |
| 70 | |
| 71 | # Save to the target file if provided |
| 72 | if save: |
no test coverage detected