You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的aiohttp与async函数加速API请求?代码无返回排查

问题分析与修复

你的代码返回None的核心原因是异步函数matches()没有返回值,执行results = loop.run_until_complete(matches())时,matches()结束后未返回任何内容,导致results被赋值为None,覆盖了之前全局维护的results列表。

同时,用全局变量存储结果并非异步编程的最佳实践,容易引发并发问题,建议在函数内部管理结果列表并返回。

修复后的代码

import asyncio
import aiohttp

competition = ['216718', '177489', '132739', '168769', '168770', '147735', '132822', '132823', '133015', '173636', '151636', '217971', '217838', '217984', '173138', '152566', '133025', '130047', '217911', '136630', '162388', '132149', '152553', '178776', '152554', '152555', '215790', '215789', '215791', '215792', '108698', '176597', '132748', '132747', '181111', '132424', '132639', '147507', '147532', '143084', '132638', '126842', '126665', '126667', '132298', '125984', '161539', '141677', '149844']
querystring1 = {"annex":"3","desktopVersion":"2.24.89","locale":"sr"}   
headers1 = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0",
    "Accept": "application/json, text/plain, */*",
    "Accept-Language": "en-US,en;q=0.5",
    "Accept-Encoding": "gzip, deflate, br",
    "X-INSTANA-T": "d55204082031b541",
    "X-INSTANA-S": "d55204082031b541",
    "X-INSTANA-L": "1,correlationType=web;correlationId=d55204082031b541",
    "DNT": "1",
    "Sec-GPC": "1",
    "Connection": "keep-alive",
    "Referer": "https://www.maxbet.rs/leagues/S",
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-origin",
    "TE": "trailers"
}

def get_tasks(session):
    tasks = []
    for id in competition:
        url1 = f"https://www.maxbet.rs/restapi/offer/sr/sport/S/league/{id}/mob"    
        tasks.append(session.get(url1, headers=headers1, params=querystring1))
    return tasks

async def matches():
    results = []
    async with aiohttp.ClientSession() as session:
        tasks = get_tasks(session)
        responses = await asyncio.gather(*tasks)
        for response in responses:
            # 确保响应成功再解析
            if response.status == 200:
                results.append(await response.json())
            else:
                results.append({"error": f"Status code {response.status}"})
    return results

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    results = loop.run_until_complete(matches())
    loop.close()
    print(results)

关键修改点

  • 移除全局results变量,改为在matches()函数内部创建并返回结果列表,彻底解决变量覆盖问题。
  • 使用async with管理ClientSession,自动关闭会话,比手动调用close()更安全可靠。
  • 添加响应状态码检查,避免因个别请求失败导致整个程序异常。
  • 用f-string拼接URL,代码更简洁易读。

如果之前用requests能正常获取内容,但aiohttp仍解析不到数据,可检查响应压缩处理——aiohttp默认自动处理Accept-Encoding,若遇到异常,可尝试添加connector=aiohttp.TCPConnector(force_close=True)或关闭自动解压,但从你的代码情况看,核心问题还是返回值的处理逻辑。

内容的提问来源于stack exchange,提问作者ribicapongo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:15:16