aiohttp TraceConfig请求发送回调报错:缺少chunk参数如何解决?
解决aiohttp回调缺少
chunk参数的异常 错误原因
你遇到的异常是因为NetworkUsageMonitor.on_request_chunk_sent_callback的参数签名和aiohttp回调的要求不匹配。aiohttp的request_chunk_sent回调会传入三个固定参数:session(客户端会话实例)、trace_config_ctx(追踪配置上下文)、chunk(发送的数据块),而如果这是一个类的实例方法,第一个参数还需要self,所以方法定义必须包含这四个参数,否则会出现参数缺失的错误。
修复后的完整代码
import asyncio import aiohttp from aiohttp import TraceConfig class NetworkUsageMonitor: def __init__(self): self.total_sent = 0 self.total_received = 0 # 修正参数签名:self + aiohttp要求的三个参数 def on_request_chunk_sent_callback(self, session, trace_config_ctx, chunk): self.total_sent += len(chunk) def on_response_chunk_received_callback(self, session, trace_config_ctx, chunk): self.total_received += len(chunk) async def traffic_monitor_task(self): # 每秒输出一次流量统计,模拟任务管理器的实时显示 while True: sent_kb = self.total_sent / 1024 received_kb = self.total_received / 1024 print(f"已发送: {sent_kb:.2f} KB | 已接收: {received_kb:.2f} KB") await asyncio.sleep(1) async def sample_request_task(self): # 创建追踪配置并绑定回调 trace_config = TraceConfig() trace_config.on_request_chunk_sent.append(self.on_request_chunk_sent_callback) trace_config.on_response_chunk_received.append(self.on_response_chunk_received_callback) # 带追踪配置的客户端会话 async with aiohttp.ClientSession(trace_configs=[trace_config]) as session: # 这里替换成你实际的请求逻辑,示例为循环请求example.com while True: async with session.get("http://example.com") as resp: await resp.text() # 读取响应内容才会触发接收回调 await asyncio.sleep(3) async def main(): monitor = NetworkUsageMonitor() # 并发运行监控任务和请求任务 await asyncio.gather( monitor.traffic_monitor_task(), monitor.sample_request_task() ) if __name__ == "__main__": asyncio.run(main())
关键修复点
- 回调参数签名修正:确保
on_request_chunk_sent_callback和on_response_chunk_received_callback的参数顺序为self, session, trace_config_ctx, chunk,完全匹配aiohttp的回调传参规则。 - 正确绑定回调:直接将实例方法添加到
TraceConfig的对应事件列表中,实例方法会自动携带self参数,无需额外包装。 - 并发任务设计:通过
asyncio.gather同时运行流量监控任务和请求任务,实现实时统计输出。
内容的提问来源于stack exchange,提问作者ziivittskiy
相关产品推荐
相关产品推荐

