[python] aiohttp를 사용하여 비동기적으로 파일 압축 및 압축 해제하기

파일 압축과 압축 해제는 일반적으로 동기적으로 처리되지만, 오늘은 aiohttp 라이브러리를 사용하여 비동기적으로 파일을 압축하고 해제하는 방법을 알아보겠습니다. aiohttp는 파이썬에서 비동기 웹 서버 및 클라이언트 개발을 위한 라이브러리로 널리 사용됩니다.

필요한 패키지 설치

먼저, aiohttp 패키지를 설치해야 합니다. 아래 명령을 사용하여 패키지를 설치하세요.

pip install aiohttp

파일 압축하기

다음 예제 코드는 비동기적으로 파일을 압축하는 방법을 보여줍니다.

import aiohttp
import asyncio
import zipfile

async def compress_file(file_path, destination_path):
    async with aiohttp.ClientSession() as session:
        async with session.get(file_path) as response:
            if response.status == 200:
                with open(destination_path, 'wb') as file:
                    async for data in response.content.iter_any():
                        file.write(data)
        zipfile.ZipFile(destination_path + '.zip', 'w').write(destination_path)
        print(f'File compressed successfully: {destination_path}.zip')

async def main():
    await compress_file('http://example.com/file.txt', 'file.txt')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

위의 코드는 compress_file 함수를 정의하고, aiohttp를 사용하여 주어진 파일을 다운로드한 후, 해당 파일을 압축합니다. 다운로드 받은 파일은 압축 후 삭제합니다. 메인 함수에서는 compress_file 함수를 비동기적으로 실행합니다.

파일 압축 해제하기

다음 예제 코드는 aiohttp를 사용하여 압축 해제하는 방법을 보여줍니다.

import aiohttp
import asyncio
import zipfile

async def decompress_file(zipfile_path, destination_path):
    async with aiohttp.ClientSession() as session:
        async with session.get(zipfile_path) as response:
            if response.status == 200:
                zip_data = await response.content.read()
                with open('temp.zip', 'wb') as file:
                    file.write(zip_data)
                with zipfile.ZipFile('temp.zip', 'r') as zip_ref:
                    zip_ref.extractall(destination_path)
                print(f'File decompressed successfully: {destination_path}')

async def main():
    await decompress_file('http://example.com/file.zip', 'destination_folder')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

위의 코드는 decompress_file 함수를 정의하고, aiohttp를 사용하여 주어진 압축 파일을 다운로드한 후, 해당 파일을 해제합니다. 해제된 파일은 지정된 목적지 폴더에 저장됩니다. 메인 함수에서는 decompress_file 함수를 비동기적으로 실행합니다.

결론

위의 예제 코드는 aiohttp를 사용하여 비동기적으로 파일 압축 및 압축 해제하는 방법을 보여주었습니다. aiohttp를 활용하면 동기적으로 처리하는 것보다 더 효율적이고 빠른 파일 작업을 수행할 수 있습니다. aiohttp를 사용하여 비동기 작업을 처리하는 방법에 익숙해지면, 다양한 비동기 작업을 더욱 효율적으로 처리할 수 있을 것입니다.

참고 자료