aiohttp.client_exceptions.ClientConnectorError:无法连接到主机 example.com:端口 ssl:默认 [连接调用失败('IP',PORT)]

问题描述 投票:0回答:1

我正在发出请求以查找状态,应该发送请求直到达到该状态,但是,当超过 25 个“同时”连接时,它会给出连接错误,我已经尝试设置 ssl=False 并且也使用 sslcontext,我尝试了 aiohttp。连接器(限制=1000,limit_per_host=1000) 老实说,没有任何效果

记住低于 25 个请求它可以正常工作

import aiohttp
import asyncio
import sys

if sys.platform == 'win32':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())


async def proccess_status(headers, payload):
    await asyncio.sleep(0.3)

    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=10000, limit_per_host=10000), trust_env=True) as session:
        while True:
            async with session.post("https://example.com", headers=headers, data=payload) as response:
                try:
                    #print(response)
                    pass
                
                except Exception as error:
                    print(error)


async def main():
    number_of_requests = 50
    timeout = 18000  # Timelimit in seconds
    headers = {}
    payload = "random_payload"

    tasks = [asyncio.create_task(proccess_status(headers, payload)) for _ in range(number_of_requests)]
    
    results, pending_tasks = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED, timeout=timeout)
    
    if results:
        first_task_done = results.pop()
        value = first_task_done.result()
    else:
        print("No requests were completed within the time limit.")
    
    for task in pending_tasks:
        task.cancel()

    return value


if __name__ == "__main__":
    asyncio.run(main())

我的期望:

https://example.com) [200 OK]> ', '内容编码': 'br', '日期': 'Sun, 2024 年 1 月 21 日 17:02:57 GMT', 'Timing-Allow-Origin': '')>

我得到了什么: aiohttp.client_exceptions.ClientConnectorError:无法连接到主机 example.com:端口 ssl:默认 [连接调用失败('IP',PORT)]

python-3.x aiohttp
1个回答
0
投票

您的问题对于您想要实现的目标有点模糊。但是,如果只是将其限制为 25 个同时请求,那么只需添加信号量就可以作为快速解决方案。

async def process_status(headers, payload, sem):
    async with sem:
        ...

async def main():
    sem = asyncio.Semaphore(25)
    tasks = (asyncio.create_task(process_status(headers, payload, sem) for ...)

请注意,这仍然会在内存中创建所有任务,因此更好的解决方案可能会涉及某种在任何给定时间仅创建 25 个任务的队列。

© www.soinside.com 2019 - 2024. All rights reserved.