使用Aiogoogle调用Google Calendar接口未实现异步执行问题
解决Aiogoogle请求无法并行执行的问题
你的代码逻辑框架是正确的,但请求串行执行可能由以下原因导致,对应修复方案如下:
1. 显式创建异步任务
虽然asyncio.gather支持直接传入协程对象,但显式用asyncio.create_task包装每个请求,能确保它们被调度为并行执行的独立任务。修改tasks生成代码:
tasks = [asyncio.create_task( aiogoogle.as_user( service.events.list(timeMin=timeMin, timeMax=timeMax, calendarId=CALENDAR_ID) ) ) for timeMin, timeMax in ranges_list]
2. 排查事件循环阻塞
检查代码中是否存在同步IO操作(如同步文件读写、同步数据库调用),这类操作会阻塞事件循环,迫使异步请求串行执行。如果有,需替换为对应的异步实现。
3. 强制指定异步HTTP客户端
Aiogoogle默认使用aiohttp作为异步客户端,但环境冲突或配置异常可能导致其 fallback 到同步客户端,可显式指定客户端类型:
from aiogoogle.sessions.aiohttp_session import AiohttpSession async with Aiogoogle( user_creds=user_creds, client_creds=client_creds, session_factory=AiohttpSession ) as aiogoogle: # 后续业务代码保持不变
4. 验证并行执行状态
添加时间戳日志,直观确认请求是否真的并行:
async def fetch_events(aiogoogle, service, timeMin, timeMax): start = datetime.now() print(f"启动请求: {timeMin[:10]} | 时间: {start}") result = await aiogoogle.as_user( service.events.list(timeMin=timeMin, timeMax=timeMax, calendarId=CALENDAR_ID) ) end = datetime.now() print(f"完成请求: {timeMin[:10]} | 耗时: {end - start}") return result async def list_events(ranges_list: tuple[datetime, datetime]): async with Aiogoogle(user_creds=user_creds, client_creds=client_creds) as aiogoogle: service = await aiogoogle.discover("calendar", "v3") tasks = [asyncio.create_task(fetch_events(aiogoogle, service, timeMin, timeMax)) for timeMin, timeMax in ranges_list] results = await asyncio.gather(*tasks) return [[event['summary'] for event in calendar['items']] for calendar in results]
运行后若所有请求的启动时间接近,说明并行逻辑已生效。
内容的提问来源于stack exchange,提问作者Francesco Fadda
相关产品推荐
相关产品推荐

