扩展 requests.Response 类的明智方法?

nls*_*bch 6 python-3.x python-requests

我正在尝试延长requests.Response,但我不知道如何去做。

我想要的是延长requests.Response。我看到的问题是我必须创建一个全新的库分支,或者至少创建一个自定义适配器并为此实现自定义代码。

我目前正在将响应存储在新类的属性中,但这意味着我的自定义APIResponse实际上并不像扩展requests.Response对象那样运行。

这是我目前的虚拟工作。

class APIResponse:
    def __init__(self, req_response, formatted_json=None):
        self._content = req_response._content
        self._response = req_response

    @property
    def response(self):
        return self._response
Run Code Online (Sandbox Code Playgroud)

如上所述,我希望我的自定义类表现得像一个requests.Response对象,并具有一些额外的功能。由于Response对象是在非常低的级别(即库HTTPAdapter中的模块)生成的requests,因此我还必须编写一个自定义适配器 - 并且从逻辑上讲,还要自定义调用requests.Sessions它的类。

这一切都让我相信我在这里错过了一些东西。

是否有一种明智的方法来扩展request.Response对象,而无需大量代码?

我也尝试过在实例化Response对象周围“包装”一个类,但它看起来很老套:

class APIResponse(Response):
    __attrs__ = ['_content', 'status_code', 'headers', 'url', 'history',
                 'encoding', 'reason', 'cookies', 'elapsed', 'request',
                 '_formatted']

    def __init__(self, req_response):
        self._content = req_response._content
        self._content_consumed = req_response._content_consumed
        self.status_code = req_response.status_code
        self.headers = req_response.headers
        self.url = req_response.url
        self.history = req_response.history
        self.encoding = req_response.encoding
        self.reason = req_response.reason
        self.cookies = req_response.cookies
        self.elapsed = req_response.elapsed
        self.request = req_response.request
Run Code Online (Sandbox Code Playgroud)

Loi*_*icM 3

当看到你的“hacky”时,首先想到的是它有工作的优势。

但是,存在您可能忘记要使用的方法所需的一些属性的风险:为什么不简单地迭代 __dict__ 属性来创建包装器?

这是它的样子:

class APIResponse(Response):
    def __init__(self, req_response):
        for k, v in req_response.__dict__.items():
            self.__dict__[k] = v
Run Code Online (Sandbox Code Playgroud)

它使代码更加紧凑,但我不得不承认它仍然很hacky。