Python 请求中的 SSLError(读取操作超时)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24196264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:10:59  来源:igfitidea点击:

SSLError (Read operation timed out) in Python requests

pythonsslpython-requests

提问by rrlamichhane

I have a python API script and my script sometimes gets terminated on this line despite using try/except. Here is the code:

我有一个 python API 脚本,尽管使用try/except. 这是代码:

    try:
            r = requests.post(URL, data=params, headers=headers, timeout=self.request_timeout)
            try:
                response = r.json()
            except Exception, e:
                message = "ERROR_0104! Unexpected error occured. The error is: "
                message += str(e)
                print message
                aux_func.write_log(message)
                return 'Switch'
    except requests.exceptions.RequestException:
            print "Exception occurred on 'API requests post' procedure."
            counter += 1
            continue
    ...

The error occurs on the second line of above shown code. This is the error:

错误发生在上面显示的代码的第二行。这是错误:

     r = requests.post(URL, data=params, headers=headers, timeout=self.request_timeout)
      File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 88, in post
        return request('post', url, data=data, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 44, in request
        return session.request(method=method, url=url, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 383, in request
        resp = self.send(prep, **send_kwargs)
      File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 486, in send
        r = adapter.send(request, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 394, in send
        r.content
      File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 679, in content
        self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
      File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 616, in generate
        decode_content=True):
      File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/response.py", line 236, in stream
        data = self.read(amt=amt, decode_content=decode_content)
      File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/response.py", line 183, in read
        data = self._fp.read(amt)
      File "/usr/lib/python2.7/httplib.py", line 543, in read
        return self._read_chunked(amt)
      File "/usr/lib/python2.7/httplib.py", line 585, in _read_chunked
        line = self.fp.readline(_MAXLINE + 1)
      File "/usr/lib/python2.7/socket.py", line 476, in readline
        data = self._sock.recv(self._rbufsize)
      File "/usr/lib/python2.7/ssl.py", line 305, in recv
        return self.read(buflen)
      File "/usr/lib/python2.7/ssl.py", line 224, in read
        return self._sslobj.read(len)
    ssl.SSLError: The read operation timed out

I presume something within the Requests module is causing this, but I don't know what.

我认为 Requests 模块中的某些内容导致了这种情况,但我不知道是什么。

采纳答案by Veedrac

The read operation has timed out, as it says.

正如它所说,读取操作已超时。

It times out, however, with an ssl.SSLError. This is notwhat your exceptis catching. If you want to catch and retry, you need to catch the right error.

但是,它超时了ssl.SSLError。这不是except要捕捉的。如果要捕获并重试,则需要捕获正确的错误。

回答by rrlamichhane

I saw that there was some confusion here regarding what the solution is because of lack of enough details. I posted the answer on the comment to the top post but the formatting is not great in the comment section and I will post a properly formatted answer here.

我看到由于缺乏足够的细节,这里有一些关于解决方案的困惑。我将评论的答案发布到顶部帖子,但评论部分的格式不是很好,我将在此处发布格式正确的答案。

The problem, as Veedrac has mentioned is that I was not catching all the possible exceptions in the code that I posted in the question. My code only catches "requests.exceptions.RequestException", and any other exception will cause the code to exit abruptly.

正如 Veedrac 所提到的,问题在于我没有在问题中发布的代码中捕获所有可能的异常。我的代码只捕获“requests.exceptions.RequestException”,任何其他异常都会导致代码突然退出。

Instead, I'm gonna re-write the code like this:

相反,我将重新编写这样的代码:

try:
        r = requests.post(URL, data=params, headers=headers, timeout=self.request_timeout)
        try:
            response = r.json()
        except Exception, e:
            message = "ERROR_0104! Unexpected error occured. The error is: "
            message += str(e)
            print message
            aux_func.write_log(message)
            return 'Switch'
except requests.exceptions.RequestException:
        print "Exception occurred on 'API requests post' procedure."
        counter += 1
        continue
except Exception, e:
        print "Exception {0} occurred".format(e)
        continue

All I did was add an extra generic exception catcher at the end which will catch all other unaccounted for exceptions.

我所做的只是在最后添加一个额外的通用异常捕获器,它将捕获所有其他未说明的异常。

I hope this helps.

我希望这有帮助。

Thanks.

谢谢。

回答by rrlamichhane

except Exception, edoes not work with >= Python 3 You have to make it except Exception as e

except Exception, e不适用于 >= Python 3 你必须让它 except Exception as e