Skip to main content

examples/downloading.py

1#!/usr/bin/env python
2"""
3Download a collection of images from https://http.cat/.
5Rather than downloading the images one-by-one, it runs multiple instances
6of the download() function to complete the process faster.
7"""
9import tempfile
10import urllib.request
12from concurrently import concurrently
15def save_http_cat(status_code):
16 """
17 Save the JPEG from https://http.cat/ associated with this status code.
19 Returns the path to the downloaded file.
20 """
21 _, path = tempfile.mkstemp(suffix=f"_{status_code}.jpg")
22 urllib.request.urlretrieve(f"https://http.cat/{status_code}", path)
23 return path
26if __name__ == "__main__":
27 codes = [200, 201, 202, 301, 302, 400, 405, 410, 418, 420, 451, 500]
29 for input, output in concurrently(save_http_cat, inputs=codes):
30 print(input, output)