[python] aiohttp를 사용하여 비동기 파일 업로드 및 다운로드 처리하기

목차

소개

aiohttp는 파이썬에서 비동기 웹 서버 및 클라이언트를 구축하기 위한 라이브러리입니다. 이 라이브러리를 사용하여 파일 업로드 및 다운로드와 같은 작업을 비동기적으로 처리할 수 있습니다.

이번 글에서는 aiohttp를 사용하여 비동기 파일 업로드와 다운로드 작업을 처리하는 방법에 대해 알아보겠습니다.

비동기 파일 업로드

비동기 파일 업로드를 위해 먼저 파일을 업로드할 서버의 URL을 설정해야 합니다. 그리고 aiohttp.ClientSession를 사용하여 비동기 세션을 생성하고 파일을 업로드하는 upload_file 함수를 작성합니다.

import aiohttp

async def upload_file(file_path):
    url = "https://example.com/upload"
    
    async with aiohttp.ClientSession() as session:
        async with session.post(url, data=file_path) as response:
            if response.status == 200:
                print("File uploaded successfully")
            else:
                print("Failed to upload file")

file_path = "path/to/file.txt"
asyncio.run(upload_file(file_path))

위의 코드에서는 aiohttp.ClientSession로 세션을 생성하고, session.post를 사용하여 파일을 POST 요청으로 업로드합니다. 서버의 응답 상태 코드에 따라 성공 또는 실패 메시지를 출력합니다.

비동기 파일 다운로드

비동기 파일 다운로드를 위해서도 마찬가지로 파일을 다운로드할 서버의 URL을 설정해야 합니다. 아래 코드에서는 aiohttp.ClientSession로 세션을 생성하고 파일을 다운로드하는 download_file 함수를 작성합니다.

import aiohttp

async def download_file(url, save_path):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            if response.status == 200:
                with open(save_path, "wb") as file:
                    file.write(await response.read())
                    print("File downloaded successfully")
            else:
                print("Failed to download file")

file_url = "https://example.com/file.txt"
save_path = "path/to/save/file.txt"
asyncio.run(download_file(file_url, save_path))

위의 코드에서는 aiohttp.ClientSession로 세션을 생성하고, session.get을 사용하여 파일을 GET 요청으로 다운로드합니다. 서버의 응답 상태 코드에 따라 파일을 저장하고 성공 또는 실패 메시지를 출력합니다.

결론

aiohttp를 사용하여 비동기 파일 업로드 및 다운로드 작업을 처리하는 방법에 대해 알아보았습니다. 이를 통해 웹 개발에서 비동기 처리를 효과적으로 활용할 수 있습니다. 추가적으로 asyncio를 사용하여 비동기적으로 파일 업로드 및 다운로드 작업을 실행할 수 있습니다. 참고 자료를 통해 더 자세한 정보를 확인하시기 바랍니다.

참고 자료