|
6 | 6 | import requests |
7 | 7 |
|
8 | 8 |
|
9 | | -# Function for download file parameter taking as url |
10 | | - |
| 9 | +def download(url, filename): |
| 10 | + try: |
| 11 | + with requests.get(url, stream=True, timeout=10) as response: |
| 12 | + response.raise_for_status() # Raises error for 4xx/5xx |
11 | 13 |
|
12 | | -def download(url): |
13 | | - f = open( |
14 | | - "file_name.jpg", "wb" |
15 | | - ) # opening file in write binary('wb') mode with file_name.ext ext=extension |
16 | | - f.write(requests.get(url).content) # Writing File Content in file_name.jpg |
17 | | - f.close() |
18 | | - print("Succesfully Downloaded") |
| 14 | + with open(filename, "wb") as file: |
| 15 | + for chunk in response.iter_content(chunk_size=8192): |
| 16 | + if chunk: |
| 17 | + file.write(chunk) |
19 | 18 |
|
| 19 | + print(f"Successfully downloaded: {filename}") |
20 | 20 |
|
21 | | -# Function is do same thing as method(download) do,but more strict |
22 | | -def download_2(url): |
23 | | - try: |
24 | | - response = requests.get(url) |
25 | | - except Exception: |
26 | | - print("Failed Download!") |
27 | | - else: |
28 | | - if response.status_code == 200: |
29 | | - with open("file_name.jpg", "wb") as f: |
30 | | - f.write(requests.get(url).content) |
31 | | - print("Succesfully Downloaded") |
32 | | - else: |
33 | | - print("Failed Download!") |
| 21 | + except requests.exceptions.RequestException as e: |
| 22 | + print(f"Download failed: {e}") |
34 | 23 |
|
35 | 24 |
|
36 | | -url = "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4" # URL from which we want to download |
| 25 | +# Example usage |
| 26 | +url = "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4" |
| 27 | +download(url, "avatar.jpg") |
37 | 28 |
|
38 | | -download(url) |
0 commit comments