### 详解Python `requests` 超时与重试机制 在进行网络编程时,处理好超时问题是非常重要的一步,特别是在使用 Python 的 `requests` 库时更是如此。本篇文章将详细介绍如何在 `requests` 库中设置超时以及如何实现超时后的重试逻辑。 #### 一、理解超时概念 在 `requests` 库中,超时分为两种类型:连接超时(`connect timeout`)和读取超时(`read timeout`)。 1. **连接超时**: - 连接超时指的是客户端在建立与服务器的连接过程中所等待的最大时间。 - 如果在这个时间内连接未能建立,就会触发连接超时异常。 - 例如: ```python import time import requests url = 'http://www.google.com.hk' print(time.strftime('%Y-%m-%d %H:%M:%S')) try: html = requests.get(url, timeout=5).text print('success') except requests.exceptions.RequestException as e: print(e) print(time.strftime('%Y-%m-%d %H:%M:%S')) ``` 2. **读取超时**: - 读取超时是指一旦客户端与服务器成功建立连接后,等待服务器响应数据的最大时间。 - 如果服务器在指定时间内没有发送任何数据,则触发读取超时异常。 - 示例代码: ```python import time import requests url_login = 'http://www.heibanke.com/accounts/login/?next=/lesson/crawler_ex03/' session = requests.Session() session.get(url_login) token = session.cookies['csrftoken'] session.post(url_login, data={'csrfmiddlewaretoken': token, 'username': 'guliang21', 'password': '123qwe'}) print(time.strftime('%Y-%m-%d %H:%M:%S')) url_pw = 'http://www.heibanke.com/lesson/crawler_ex03/pw_list/' try: html = session.get(url_pw, timeout=(5, 10)).text print('success') except requests.exceptions.RequestException as e: print(e) print(time.strftime('%Y-%m-%d %H:%M:%S')) ``` - 注意:如果没有显式设置超时时间,`requests` 将使用默认值。对于连接超时,默认为 None,意味着没有限制;而对于读取超时,默认值同样为 None。 #### 二、超时参数设置 1. **设置单个超时值**: - 如果只需要设置一个超时值(适用于连接和读取),可以简单地将超时值作为 `timeout` 参数传递给 `get()` 或 `post()` 方法。 - 示例: ```python r = requests.get('https://github.com', timeout=5) ``` 2. **分别设置连接和读取超时**: - 如果需要分别设置连接超时和读取超时,可以通过传递一个包含两个元素的元组来实现。 - 示例: ```python r = requests.get('https://github.com', timeout=(3.05, 27)) ``` #### 三、实现超时重试逻辑 在实际应用中,往往需要在遇到超时或其他网络异常时实现自动重试机制。这可以通过循环或使用第三方库如 `retrying` 来实现。 1. **基础重试逻辑**: - 可以通过简单的 `while` 循环来实现重试逻辑。 ```python import time from requests.exceptions import RequestException def fetch_data(url, max_retries=3): retries = 0 while retries < max_retries: try: response = requests.get(url, timeout=5) if response.status_code == 200: return response.text else: raise RequestException("Bad status code: " + str(response.status_code)) except RequestException as e: print(e) retries += 1 time.sleep(2) # 等待2秒后重试 return None url = 'http://example.com' result = fetch_data(url) print(result) ``` 2. **使用第三方库 `retrying`**: - `retrying` 库提供了一种更灵活的方式来管理重试逻辑。 - 安装 `retrying`: ``` pip install retrying ``` - 示例: ```python from retrying import retry import requests @retry(stop_max_attempt_number=3, wait_fixed=2000) def fetch_data(url): response = requests.get(url, timeout=5) if response.status_code == 200: return response.text else: raise Exception("Bad status code: " + str(response.status_code)) url = 'http://example.com' result = fetch_data(url) print(result) ``` ### 总结 本文详细介绍了在使用 Python `requests` 库时如何设置超时,并实现了超时后的重试逻辑。了解并正确使用这些功能可以帮助开发者更好地处理网络请求中的不稳定因素,提高程序的健壮性。
























- 粉丝: 4
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


最新资源
- 计算机网络营销在电子商务中的应用分析.docx
- 基于网络影视课程编导理念的微课教学设计研究.docx
- 案例教学法在网络远程培训中的应用研究.docx
- Web3.0时代农村电子商务发展的困境与出路.docx
- 小微企业办公自动化系统设计与实现-江公亚.doc
- 2018年度大数据时代的互联网信息安全试题及答案(100分).docx
- PLC的全自动洗衣机控制系统课程设计方案.doc
- 长袋脉冲除尘设备PLC电气控制标准系统.doc
- 程序设计基础课程设计指导书.doc
- 项目管理中如何管理好自己的团队.docx
- 数据库原理与应用孟凡荣闫秋艳课后习题答案.doc
- 浅析中职计算机教学中的德育渗透.docx
- 电气工程及其自动化(城轨供电)专业培养方案.doc
- 数据电文的证据属性与网络公证探析.docx
- 单片机课程设计方案八路抢答器).doc
- 谈对互联网金融在线支付风险的有效措施.docx


