python问题:asyncio比ThreadPool更慢如何解释?附deepl-pro实测

应该是httpx异步的实现有问题吧,换aiohttp就不分伯仲了

  • aiohttp
    image

  • httpx
    image

async def deepl_tr_async_aiohttp(text: str, source_lang: str = "auto", target_lang: str = "") -> Union[dict, Exception]:
    """Translate using deeplpro's dl_session cookie."""
    if not source_lang.strip():
        source_lang = "auto"

    if not target_lang.strip():
        target_lang = "zh"

    data = {
        "jsonrpc": "2.0",
        "method": "LMT_handle_texts",
        "id": randrange(sys.maxsize),
        "params": {
            "splitting": "newlines",
            "lang": {
                "source_lang_user_selected": source_lang,
                "target_lang": target_lang,
            },
            "texts": [
                {
                    "text": text,
                    "requestAlternatives": 3,
                }
            ],
        },
    }

    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(URL, json=data, headers=HEADERS) as response:
                response.raise_for_status()
                jdata = await response.json()
                return jdata
        except Exception as exc:
            return exc
1 个赞