- 请求教程
- 请求 - 主页
- 请求 - 概述
- 请求 - 环境设置
- 请求 - Http 请求如何工作?
- 请求 - 处理请求
- 处理 HTTP 请求的响应
- 请求 - HTTP 请求标头
- 请求 - 处理 GET 请求
- 处理 POST、PUT、PATCH 和 DELETE 请求
- 请求 - 文件上传
- 请求 - 使用 Cookie
- 请求 - 处理错误
- 请求 - 处理超时
- 请求 - 处理重定向
- 请求 - 处理历史记录
- 请求 - 处理会话
- 请求 - SSL 认证
- 请求 - 身份验证
- 请求 - 事件挂钩
- 请求 - 代理
- 请求 - 使用请求进行网页抓取
- 请求有用的资源
- 请求 - 快速指南
- 请求 - 有用的资源
- 请求 - 讨论
请求 - 事件挂钩
我们可以使用事件挂钩将事件添加到请求的 URL。在下面的示例中,我们将添加一个回调函数,该函数将在响应可用时被调用。
例子
要添加回调,我们需要使用 hooks 参数,如下例所示 -
import requests def printData(r, *args, **kwargs): print(r.url) print(r.text) getdata = requests.get('https://jsonplaceholder.typicode.com/users', hooks={'response': printData})
输出
E:\prequests>python makeRequest.py https://jsonplaceholder.typicode.com/users [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ]
您还可以调用多个回调函数,如下所示 -
例子
import requests def printRequestedUrl(r, *args, **kwargs): print(r.url) def printData(r, *args, **kwargs): print(r.text) getdata = requests.get('https://jsonplaceholder.typicode.com/users', hooks = {'response': [printRequestedUrl, printData]})
输出
E:\prequests>python makeRequest.py https://jsonplaceholder.typicode.com/users [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ]
您还可以将挂钩添加到创建的会话中,如下所示 -
例子
import requests def printData(r, *args, **kwargs): print(r.text) s = requests.Session() s.hooks['response'].append(printData) s.get('https://jsonplaceholder.typicode.com/users')
输出
E:\prequests>python makeRequest.py [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ]