gevent+requests在Python3.6环境下的无限递归问题解决

背景

原来接口测试项目使用的grequests库, 在Python3.5环境下正常, 在Python3.6环境下报如下错误:

Traceback (most recent call last):
...
  File "D:\Program Files\Python\lib\site-packages\requests\api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "D:\Program Files\Python\lib\site-packages\requests\api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "D:\Program Files\Python\lib\site-packages\requests\sessions.py", line 512, in request
    resp = self.send(prep, **send_kwargs)
  File "D:\Program Files\Python\lib\site-packages\requests\sessions.py", line 622, in send
    r = adapter.send(request, **kwargs)
  File "D:\Program Files\Python\lib\site-packages\requests\adapters.py", line 445, in send
    timeout=timeout
  File "D:\Program Files\Python\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "D:\Program Files\Python\lib\site-packages\urllib3\connectionpool.py", line 343, in _make_request
    self._validate_conn(conn)
  File "D:\Program Files\Python\lib\site-packages\urllib3\connectionpool.py", line 849, in _validate_conn
    conn.connect()
  File "D:\Program Files\Python\lib\site-packages\urllib3\connection.py", line 344, in connect
    cert_reqs=resolve_cert_reqs(self.cert_reqs),
  File "D:\Program Files\Python\lib\site-packages\urllib3\util\ssl_.py", line 292, in create_urllib3_context
    context.options |= options
  File "D:\Program Files\Python\lib\ssl.py", line 467, in options
    super(SSLContext, SSLContext).options.__set__(self, value)
  File "D:\Program Files\Python\lib\ssl.py", line 467, in options
    super(SSLContext, SSLContext).options.__set__(self, value)
  File "D:\Program Files\Python\lib\ssl.py", line 467, in options
    super(SSLContext, SSLContext).options.__set__(self, value)
  [Previous line repeated 320 more times]
  File "D:\Program Files\Python\lib\ssl.py", line 465, in options
    @options.setter
RecursionError: maximum recursion depth exceeded while calling a Python object

分析

  1. 定位具体出错的语句, 是在运行调用了grequests之后的测试用例之后, 必现该错误;
  2. grequests依赖requests与gevent, 而其他用例依赖requests库的情况下不会出现该错误, 因此判断为gevent的问题;
  3. Python3.5情况下正常, 可能是gevent与Python3.6之间的兼容性问题;
  4. 谷歌搜索 "gevent python3.6 ssl maximum", 得到解决办法: https://github.com/gevent/gevent/issues/941

解决

程序的入口调用一次gevent.monkey.patch_all()即可, 具体如下:

import gevent.monkey
gevent.monkey.patch_all()

你可能感兴趣的:(gevent+requests在Python3.6环境下的无限递归问题解决)