[python] Requests 라이브러리에서 업로드 중간 상태를 표시하는 방법은?

먼저 tqdm 라이브러리를 설치해야 합니다. 다음 명령을 사용하여 설치할 수 있습니다:

pip install tqdm

requests 라이브러리로 파일을 업로드할 때 progress_callback 함수를 정의하여 업로드 상태를 처리할 수 있습니다. 이 함수는 업로드 중간 상태를 표시하고 싶은 방법을 정의하는 데 사용됩니다. 다음은 업로드 진행 상태를 출력하는 예제 코드입니다:

import requests
from tqdm import tqdm

def progress_callback(chunk_number, chunk_size, total_size):
    percent = float(chunk_number * chunk_size) / total_size * 100
    tqdm.write(f"Uploaded {percent:.2f}%")

file_path = 'path_to_file'  # 업로드할 파일 경로
url = 'upload_url'  # 업로드할 URL

with open(file_path, 'rb') as file:
    file_size = os.path.getsize(file_path)
    with tqdm(total=file_size, unit='B', unit_scale=True) as pbar:
        response = requests.post(url, data=file, headers={'Content-Disposition': f'filename={file_path}'},
                                 stream=True, timeout=None, hooks={'response': lambda r, *args, **kwargs: pbar.update(len(r.content))},
                                 files={'file': file})

위 코드에서 progress_callback 함수는 현재 업로드된 바이트 수와 전체 파일 크기를 기반으로 업로드 진행 상태를 계산합니다. 그런 다음 tqdm을 사용하여 진행 표시줄을 업데이트하고 업로드 상태를 출력합니다.

위 코드를 사용하여 파일 업로드 중간 상태를 표시할 수 있습니다. tqdmtotal 매개변수를 사용하여 전체 파일 크기를 지정하고, update 메서드를 사용하여 현재 업로드된 바이트 수를 업데이트합니다.

자세한 내용은 tqdm 공식 문서를 참조하십시오.