Skip to main content
 首页 » 编程设计

Python requests hook 返回值导致异常

2025年05月04日9findumars

Documentation对于 python requests 模块,对于 hooks 说“如果回调函数返回一个值,则假定它将替换传入的数据。如果该函数不返回任何内容,则不会影响任何其他内容”

现在我试图从我的钩子(Hook)函数返回一个值(在我的例子中是 int),它抛出了一个异常。当返回值是一个没有为其定义 raw() 方法的对象时,这在所有情况下都是有效的。

代码如下

def hook(resp,**kwargs): 
    print resp.url 
    return 1 
 
def main() 
    s = requests.Session() 
    s.hooks = {"response":hook} 
    r = s.get("http://localhost/index.html") 

这里是异常(exception):

http://localhost/index.html 
Traceback (most recent call last): 
 File "/home/talha/ws/test.py", line 85, in <module> 
   main() 
 File "/home/talha/ws/test.py", line 72, in main 
   r = s.get("http://localhost/index.html") 
 File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 347, in get 
   return self.request('GET', url, **kwargs) 
 File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 335, in request 
   resp = self.send(prep, **send_kwargs) 
 File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 446, in send 
   extract_cookies_to_jar(self.cookies, request, r.raw) 
 AttributeError: 'int' object has no attribute 'raw' 

session.py @line 446 中的代码试图在 dispatch_hook..From source 之后提取 cookie

    # Response manipulation hooks 
    r = dispatch_hook('response', hooks, r, **kwargs) 
 
    # Persist cookies 
    extract_cookies_to_jar(self.cookies, request, r.raw) 

要么需要更改文档,要么需要重新处理。处理此问题的最佳方法是什么?

[更新]

根据评论,我尝试返回基础 response 对象。事实证明它也不能以这种方式使用,因为它的一些字段被初始化为 None。

较新的代码:

def hook(resp, **kwargs): 
    obj = requests.Response() 
    return obj 

现在抛出异常:

Traceback (most recent call last): 
File "/home/talha/ws/test.py", line 88, in <module> 
   main() 
File "/home/talha/ws/test.py", line 75, in main 
   r = s.get("http://localhost/index.html") 
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 347, in get 
   return self.request('GET', url, **kwargs) 
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 335, in request 
   resp = self.send(prep, **send_kwargs) 
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 446, in send 
   extract_cookies_to_jar(self.cookies, request, r.raw) 
File "/usr/lib/python2.7/site-packages/requests/cookies.py", line 108, in extract_cookies_to_jar 
    res = MockResponse(response._original_response.msg) 
AttributeError: 'NoneType' object has no attribute '_original_response' 

我似乎必须实现一个完整的伪响应?

请您参考如下方法:

If the callback function returns a value, it is assumed that it is to replace the data that was passed in. If the function doesn’t return anything, nothing else is effected.

这意味着无论您返回什么,都应该取代您传递的响应对象。

文档中没有任何内容表明您可以只返回任何内容。你期望发生什么?

如果你想返回一个具有不同数据的响应,返回一些仍然像响应一样的东西。这意味着您需要子类化 requests 响应对象,或者实现提供相同 API 的东西:

from requests.models import Response 
 
class MyIntResponse(Response): 
    def __init__(self, integer): 
        super(MyIntResponse, self).__init__() 
        self._content_consumed = True 
        self._content = integer 
 
def hook(resp,**kwargs): 
    print resp.url 
    newresp = MyIntResponse(1) 
    newresp.raw = resp.raw  # copy across original HTTP response object 

您可能想从原始响应中复制一些其他属性;查看有关 Response 对象具有哪些属性的文档。