python-3.x 请求响应对象上的 Package 类

szqfcxe2  于 2023-03-20  发布在  Python
关注(0)|答案(1)|浏览(109)

我尝试添加一些可用于requests的response对象的自定义方法
1.创建requests类:

class Response():

    def __init__(self, response):
        self.response = response

    def __enter__(self):
        return self

    def validate_ok(self):
        assert self.response.status_code == 200
        assert 'result' in self.response.json()
        assert self.response.json()['status'] == 'ok'

1.重写HTTPAdapter类中的send方法以返回我的响应对象:

class OpenAPIAdapter(HTTPAdapter):

    def __init__(self, spec):
        super().__init__()
        self.spec = spec

    def send(self, request, **kwargs):
        response = super().send(request, **kwargs)
        response_data = RequestsOpenAPIResponse(response)
        return Response(response)

但是当调用requests.get时,会引发:

AttributeError: 'Response' object has no attribute 'history'

你知道怎么做吗?
我基本上想添加检查和东西到响应对象,所以我可以做:

resp = reqests.get(..)
resp.validate_a
resp.validate_c

堆栈跟踪:

app\api.py:25: in login
    response = api.post('/meh', params={
..\..\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\sessions.py:635: in post
    return self.request("POST", url, data=data, json=json, **kwargs)
app\api.py:57: in request
    return super().request(method, joined_url, *args, **kwargs)
..\..\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\sessions.py:587: in request
    resp = self.send(prep, **send_kwargs)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <app.api.PartnerAPI object at 0x0000018901D417D0>, request = <PreparedRequest [POST]>
kwargs = {'cert': None, 'proxies': OrderedDict(), 'stream': False, 'timeout': None, ...}, allow_redirects = True, stream = False
hooks = {'response': []}, adapter = <app.api.OpenAPIAdapter object at 0x0000018901D75B50>, start = 248362.5536161
r = <app.api.Response object at 0x0000018901B8C4D0>, elapsed = 0.8333374000212643

    def send(self, request, **kwargs):
        """Send a given PreparedRequest.

        :rtype: requests.Response
        """
        # Set defaults that the hooks can utilize to ensure they always have
        # the correct parameters to reproduce the previous request.
        kwargs.setdefault("stream", self.stream)
        kwargs.setdefault("verify", self.verify)
        kwargs.setdefault("cert", self.cert)
        if "proxies" not in kwargs:
            kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)

        # It's possible that users might accidentally send a Request object.
        # Guard against that specific failure case.
        if isinstance(request, Request):
            raise ValueError("You can only send PreparedRequests.")

        # Set up variables needed for resolve_redirects and dispatching of hooks
        allow_redirects = kwargs.pop("allow_redirects", True)
        stream = kwargs.get("stream")
        hooks = request.hooks

        # Get the appropriate adapter to use
        adapter = self.get_adapter(url=request.url)

        # Start time (approximately) of the request
        start = preferred_clock()

        # Send the request
        r = adapter.send(request, **kwargs)

        # Total elapsed time of the request (approximately)
        elapsed = preferred_clock() - start
        r.elapsed = timedelta(seconds=elapsed)

        # Response manipulation hooks
        r = dispatch_hook("response", hooks, r, **kwargs)

        # Persist cookies
>       if r.history:
E       AttributeError: 'Response' object has no attribute 'history'

..\..\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\sessions.py:711: AttributeError
ffscu2ro

ffscu2ro1#

您可能希望子类化Response对象。

from requests import Response

class ValidatedResponse(Response):
    def validate_ok(self):
        assert self.status_code == 200
        assert 'result' in self.json()
        assert self.json()['status'] == 'ok'

相关问题