使用Requests循环下载图片遇递归错误,用gevent后出SSLContext属性错误
图片下载中的SSL递归错误与gevent补丁后的问题
原下载代码
def download_article_picture(self): """ Downloads the article picture if available based on an input url """ for i in range(len(self._picture_link_list)): picture_url = self._picture_link_list[i] picture_filename = self._news_list["picture_filename"][i] output_folder = os.path.join(os.getcwd(), 'output') output_path = os.path.join(output_folder, picture_filename) response = requests.get(picture_url) # Download if response.status_code: fp = open(output_path, 'wb') fp.write(response.content) fp.close()
最初遇到的错误
执行代码时触发ssl模块的递归深度超限错误:
"RecursionError: maximum recursion depth exceeded" from ssl.py: `super(SSLContext, SSLContext)`
尝试的解决方法
为解决上述递归错误,引入gevent猴子补丁,添加以下代码:
import gevent.monkey gevent.monkey.patch_all() import requests
新出现的错误
添加补丁后,触发新的属性错误:
self._ctx, value AttributeError: 'SSLContext' object has no attribute '_ctx'
问题原因与解决思路
这个错误是gevent猴子补丁与当前Python/OpenSSL版本不兼容导致的——gevent在patch SSL模块时修改了SSLContext的内部实现,但版本不匹配时会出现属性缺失问题。
解决方法可以按以下优先级尝试:
- 升级gevent到最新稳定版
执行命令更新:pip install --upgrade gevent - 缩小补丁范围,跳过SSL模块
不要全量patch,只对必要模块打补丁:import gevent.monkey gevent.monkey.patch_all(ssl=False) import requests - 调整Python递归深度上限(临时方案)
如果不想用gevent,直接调大递归深度:import sys sys.setrecursionlimit(10000) # 根据实际情况调整数值 - 使用requests Session复用连接
避免重复创建SSL连接,减少递归触发概率:# 在类的__init__方法中初始化session def __init__(self): self.session = requests.Session() # 其他初始化代码 # 修改下载函数中的请求方式 response = self.session.get(picture_url)
内容的提问来源于stack exchange,提问作者fatbee7
相关产品推荐
相关产品推荐

