a closed issue in requests repo
从去年起,题为“建议:提高地位,以包括响应机构,如果有一个”的发布
westover
,他在信中写道:
他还提供了一个小的变通功能,这成为讨论转向的原因的基础
a pull request discussion
import requests
from requests.exceptions import HTTPError
def expanded_raise_for_status(res):
"""
Take a "requests" response object and expand the raise_for_status method to return more helpful errors
@param res:
@return: None
"""
try:
res.raise_for_status()
except HTTPError as e:
if res.text:
raise HTTPError('{} Error Message: {}'.format(str(e.message), res.text))
else:
raise e
return
我将此应用于我现有的类&本质上是
jwodder
还指出,它扩展/劫持
Response.raise_for_status()
调用
HTTPError(RequestsException)
raise_for_status()
由用户用来提供来自服务器响应的错误消息,通常以
assert response.status_code == 200, raise_for_status()
Response.text
(或
content
/
json
<self.status_code, self.reason, self.url>
也就是说
400 Bad Requests <url>
def raise_for_status(self):
"""Raises stored :class:`HTTPError`, if one occurred."""
http_error_msg = ''
if isinstance(self.reason, bytes):
# We attempt to decode utf-8 first because some servers
# choose to localize their reason strings. If the string
# isn't utf-8, we fall back to iso-8859-1 for all other
# encodings. (See PR #3538)
try:
reason = self.reason.decode('utf-8')
except UnicodeDecodeError:
reason = self.reason.decode('iso-8859-1')
else:
reason = self.reason
if 400 <= self.status_code < 500:
http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)
elif 500 <= self.status_code < 600:
http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)
if http_error_msg:
raise HTTPError(http_error_msg, response=self)
this reply
他进一步阐述了为什么他认为它值得一个特性,但是pull请求被拒绝了,我认为维护人员也有优点),考虑到模块的流行性和广泛的使用原因,如果不慎重/谨慎地使用,这可能会导致其他异常或更复杂的情况。