使用Python requests库下载文件并设置超时重试机制

在Python中,requests库是处理HTTP请求的常用工具。它不仅提供了简洁的API来发送各种HTTP请求,还支持文件下载。但在网络不稳定或服务器响应慢的情况下,下载可能会中断或超时。为了应对这种情况,可以通过设置超时重试机制来增强下载的稳定性。

使用 requests库下载文件

要使用 requests库下载文件,通常的做法是发送一个GET请求到目标URL,并将响应内容写入文件。下面是一个基本的示例:

import requests

def download_file(url, filename):
    response = requests.get(url)
    with open(filename, 'wb') as f:
        f.write(response.content)

download_file('https://example.com/file.zip', 'file.zip')
​
 
 

设置超时参数

requests.get函数有一个 timeout参数,可以用来设置请求的超时时间(以秒为单位)。如果在指定的时间内服务器没有响应,将会抛出一个 requests.exceptions.Timeout异常。

response = requests.get(url, timeout=10)  # 设置超时时间为10秒
​
 
 

实现超时重试机制

要实现超时重试机制,可以结合使用 try-except语句和循环。下面是一个带有重试机制的文件下载函数示例:

import requests
from requests.exceptions import Timeout

def download_file_with_retry(url, filename, retries=3, timeout=10):
    for i in range(retries):
        try:
            response = requests.get(url, timeout=timeout)
            with open(filename, 'wb') as f:
                f.write(response.content)
            print(f"Downloaded '{filename}' successfully.")
            break
        except Timeout:
            print(f"Timeout occurred, retrying... ({i + 1}/{retries})")
    else:
        print(f"Failed to download '{filename}' after {retries} retries.")

download_file_with_retry('https://example.com/file.zip', 'file.zip')
​
 
 

在上面的代码中,download_file_with_retry函数尝试下载文件,如果遇到超时,则重试指定的次数。通过调整 retries和 timeout参数,可以根据需要定制重试策略。

posted @ 2025-02-18 20:28  方缪  阅读(104)  评论(0)    收藏  举报