Python:寻找http.client.HTTPResponse对应raise_for_status的等价内置方法
问题
Python第三方库requests提供了便捷的raise_for_status方法,可自动抛出HTTPError。请问内置模块中的http.client.HTTPResponse是否有与之等价的函数?我自行编写了一段手动实现的代码,想了解是否存在可直接调用的简便内置函数来替代这段代码?
import http.client from urllib.error import HTTPError def raise_for_status(response: http.client.HTTPResponse) -> None: if response.status != 200: raise HTTPError( url=response.url, code=response.status, msg=response.reason, hdrs=response.headers, fp=response.fp, )
回答
http.client.HTTPResponse并没有内置等价于requests的raise_for_status的方法,你手动实现的逻辑是目前最直接的解决方案,不过可以做一点优化:HTTP协议中成功状态码是2xx区间(200-299),仅判断200会遗漏201、204等合法成功状态,建议把判断条件调整为覆盖整个2xx区间:
import http.client from urllib.error import HTTPError def raise_for_status(response: http.client.HTTPResponse) -> None: if not 200 <= response.status < 300: raise HTTPError( url=response.url, code=response.status, msg=response.reason, hdrs=response.headers, fp=response.fp, )
如果不想自己维护这个函数,也可以尝试使用urllib.request模块的urlopen方法,它返回的响应对象同样是HTTPResponse,但本质上仍需要你自己处理状态码判断,没有更简便的内置函数能直接替代你编写的这段逻辑。
内容的提问来源于stack exchange,提问作者Intrastellar Explorer
相关产品推荐
相关产品推荐

