對於Python請求模塊Documentation對於鉤子說:「如果回調函數返回一個值,則假定它將替換傳入的數據。如果函數doesn不返回任何東西,沒有其他的影響「Python請求鉤子返回一個值以引起異常
現在我想從我的鉤子函數返回一個值(int在我的情況下),它會引發異常。這在所有情況下都是有效的,當返回值是DOESNOT具有爲其定義的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")
這裏是例外:
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'
在sessions.py @line 446的代碼嘗試dispatch_hook..From源
後提取餅乾# 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'
什麼似乎是我將要實現一個完整的僞響應?
我的期望是這樣的意圖是回調應該返回相同的類型,因此它最終返回一個修改後的「響應」。注意:我不是一個python-requests用戶,這只是直覺。 –
我看不出什麼問題;你會得到一個響應對象,所以無論你返回什麼,都會替換該響應對象。其餘的代碼仍然期望替換是一個響應對象,這是否真的需要明確? –