Skip to content

Requests - 事件钩子

Requests - 利用事件钩子 (Event Hooks)

Section titled “Requests - 利用事件钩子 (Event Hooks)”

requests 库提供了一个事件钩子 (event hook) 系统,允许您在请求-响应周期的特定时刻附加回调函数 (callback function) 并使其执行。主要可用的钩子是 'response',它在从服务器接收到响应后、但在将响应返回给调用代码之前触发。

此功能对于日志记录、自定义指标收集或即时修改响应对象等任务非常有用。然而,对于许多常见用例,使用包装函数或自定义 Session 对象等更简单的替代方案可能更适合。

要添加回调函数,您可以向 hooks 参数传递一个字典。键是事件名称(例如,'response'),值是回调函数(或函数列表)。

钩子回调函数接收响应对象作为其第一个参数,后跟传递给原始请求方法(例如,get、post)的 *args 和 **kwargs。

import requests
def log_response_url(response, *args, **kwargs):
print(f"Hook: Request to {response.url} completed with status {response.status_code}")
# 如果需要,您可以在此处检查或修改响应
# 例如: response.hook_processed = True
print("Making request with a single hook...")
response_data = requests.get(
'https://jsonplaceholder.typicode.com/todos/1',
hooks={'response': log_response_url}
)
print("\nResponse Content:")
print(response_data.json())
Making request with a single hook...
Hook: Request to https://jsonplaceholder.typicode.com/todos/1 completed with status 200
Response Content:
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}

在此示例中,log_response_url 在接收到 GET 请求的响应后立即被调用。

您还可以为单个钩子提供一个回调函数列表。它们将按照在列表中出现的顺序执行。

import requests
def print_url(response, *args, **kwargs):
print(f"Hook 1: URL - {response.url}")
def print_status(response, *args, **kwargs):
print(f"Hook 2: Status Code - {response.status_code}")
print("Making request with multiple hooks...")
response_data = requests.get(
'https://jsonplaceholder.typicode.com/todos/2',
hooks={'response': [print_url, print_status]}
)
print("\nResponse Content:")
print(response_data.json())
Making request with multiple hooks...
Hook 1: URL - https://jsonplaceholder.typicode.com/todos/2
Hook 2: Status Code - 200
Response Content:
{'userId': 1, 'id': 2, 'title': 'quis ut nam facilis et officia qui', 'completed': False}

示例:在 Session 对象中使用钩子

Section titled “示例:在 Session 对象中使用钩子”

钩子也可以附加到 Session 对象。这些钩子将应用于使用该 session 发出的所有请求。

import requests
def session_hook_logger(response, *args, **kwargs):
print(f"Session Hook: Request to {response.url} got status {response.status_code}")
# 让我们给响应添加一个自定义属性
response.custom_processed_by_hook = True
session = requests.Session()
# Session 上的钩子以列表形式管理,因此您需要将其追加到列表中。
session.hooks['response'].append(session_hook_logger)
print("Making request with a session hook...")
response1 = session.get('https://jsonplaceholder.typicode.com/todos/3')
print(f"Response 1 processed by hook: {hasattr(response1, 'custom_processed_by_hook') and response1.custom_processed_by_hook}")
response2 = session.get('https://jsonplaceholder.typicode.com/todos/4')
print(f"Response 2 processed by hook: {hasattr(response2, 'custom_processed_by_hook') and response2.custom_processed_by_hook}")
Making request with a session hook...
Session Hook: Request to https://jsonplaceholder.typicode.com/todos/3 got status 200
Response 1 processed by hook: True
Session Hook: Request to https://jsonplaceholder.typicode.com/todos/4 got status 200
Response 2 processed by hook: True

虽然功能强大,但事件钩子是一个高级特性。请确保它们适合您的需求,因为有时它们会使请求逻辑更难理解。欲了解更多详情,请参阅事件钩子官方文档。