python - 当通过 raise_for_status 和 python-requests 引发 HTTPError 时如何包含响应

标签 python python-requests

我有一个 API,可以在发生 4xx 错误时返回 json 消息。一个例子是 {'message': 'Could not decode JWT token'} .当我处理异常时,该消息丢失了。

class HttpService:
    def __init__(self, url, token):
        self.headers={"Authorization": token}
        self.requests = Requests(url)

    def get(self, path):
        try:
            response = self.requests.get(path, headers=self.headers)
            response.raise_for_status()

            return response.json()
        except requests.exceptions.RequestException as e:
            raise HttpServiceException(e)

class HttpServiceException(Exception):
    pass

在另一个类中我有一个类似的方法

def get_user(self, user_id):
        try:
            return self.http_service.get("user/" + user_id)
        except HttpServiceException as e:
            print(e) // this prints "401 Client Error: Unauthorized for url: <url>"

我希望能够看到 {'message': 'Could not decode JWT token'}以及 401 Client Error: Unauthorized for url: <url>打印异常时的消息。 实现该目标的最佳/最简单方法是什么?

谢谢。

最佳答案

RequestException 具有 requestresponse 属性:

import requests

try:
    response = requests.get('https://httpbin.org/status/403')
    response.raise_for_status()
except requests.exceptions.RequestException as e:
    print(e.request)
    print(e.response)

关于python - 当通过 raise_for_status 和 python-requests 引发 HTTPError 时如何包含响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56419307/

相关文章:

python - 属性错误 : module 'requests' has no attribute 'Session' in pandas-DataReader

python - 为什么请求在运行函数时会返回错误?

python - POST 请求始终返回 "Disallowed Key Characters"

使用 Microsoft Face API 的 Python POST 请求错误 "image format unsupported"

c++ - 使用 Cython 最大限度地提高性能

python - 64 位 Python 中的 32 位 float 学运算

python - 范围在 imshow() 中起什么作用?

python - 如何在 Django 模板中链接表单?

带有代理的 Python 请求导致 SSLError WRONG_VERSION_NUMBER

python - 如何从文件名中提取电影标题