在for循环中运行异步函数时Asyncio + Aiohttp内存泄漏(超过500000个请求)(python)

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

我发出很多请求从不同的url获取数据。随着我的python程序运行,我的内存占用量不断增加,运行大约十分钟后我可以达到8G内存。我见过类似的问题Asyncio + Aiohttp在 for 循环(python)中运行异步函数时出现内存泄漏,但它不起作用。我的程序是这样工作的。(````是某些元素的省略)



async def add_success_callback(future, callback):
    result = await future
    callback(result)

async def fetch(session,url):
    try:
        headers = {```}
        params = {```}
        jar = aiohttp.DummyCookieJar()
        session = aiohttp.ClientSession(cookie_jar=jar)
        async with session.get(url, headers=headers, params=params, verify_ssl=False) as resp:
            return await resp.text(), await resp.read()

    except Exception:
        print(f"url: {url} error happened:")

async def fetch_all(urls):
    sem = Semaphore(100)
    connector = aiohttp.TCPConnector(limit=100)
    async with aiohttp.ClientSession() as session:
        tasks = []
        for url in urls:
            async with sem:
                task = asyncio.create_task(fetch(session, url))         
                tasks.append(task)
        await asyncio.gather(*tasks)
        datas = await asyncio.gather(*tasks, return_exceptions=True)
        return datas

def get_result(data):
    text, content = data
    soup = BeautifulSoup(text, 'html.parser')
    name = soup.find('div', class_='name').text
    chupin = soup.find('div', class_="panel-wrapper", id="出品").text
    chupindict[name] = chupin



urls=[]
chupindict = {}
for i in range(0,500000):
      url = '```'
      urls.append(url)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(fetch_all(urls))
loop.close()

这让我很困扰,但我是一名新生,我已经尝试搜索任何我能得到的信息。任何帮助将不胜感激,谢谢!

我尝试过Asyncio + Aiohttp 在 for 循环中运行异步函数时出现内存泄漏(python)[https://github.com/encode/httpx/issues/978][https://github.com/encode/ httpx/issues/978]但是对于SSL解决方案我发现它可以与httpx一起使用,我不知道是否可以在我的程序中使用。 我只是想解决内存问题,谢谢!

python memory-leaks out-of-memory python-asyncio aiohttp
1个回答
0
投票

使用memory_profiler,我发现内存问题存在于

 session = aiohttp.ClientSession(cookie_jar=jar) async with session.get(url, headers=headers, params=params, verify_ssl=False) as resp: return await resp.text(), await resp.read()
我没有正确关闭它,所以内存无法清理。修复后
        async with aiohttp.ClientSession(cookie_jar=jar) as session: async with session.get(url, headers=headers, params=params, verify_ssl=False) as resp: await session.close() return await resp.text(), await resp.read()
感谢每一条帮助我再次解决问题的评论!

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