使用aiohttp下载图像在一些迭代之后会卡住

2024-04-18 13:45:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用aiohttp异步下载一些图像文件。我的代码是:

async def save_message_images(self, message_data, channel):
    async with aiohttp.ClientSession() as session:
        image_links = []
        for i, link in enumerate(message_data.get('image_links')):
            async with session.get(link) as response:
                if response.status == 200:
                    file_name = 'media/messages_images/' + str(channel.telegram_username) + '_' + \
                               str(message_data.get('message_id') + '_' + str(i)) + '.jpg'
                    file = open(file_name, mode='wb')
                    file.write(await response.read())
                    file.close()
                    image_links.append(file_name)
                else:
                    raise MessageWebCrawler.RetrieveUrlException()
        message_data['image_links'] = image_links
        await session.close()
        return message_data

我在一个while块中运行这段代码,但是经过一段迭代aiohttp就卡住了,不再工作了。我在python 3.7.4aiohttp 3.5.4中使用ubuntu 16。有人能帮我吗?你知道吗


Tags: 代码nameimagemessagedatagetasyncaiohttp