본문 바로가기
개발로그/Python

Google Drive에 있는 파일을 다운로드하는 세가지 방법

by 그리너리디밸로퍼 2025. 3. 7.
 pip install google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2

요즘 하는 프로젝트에서 배운 3가지 다운로드 방법을 정리한다. 

 

1. requests 로 다운로드

2. gdown을 이용해서 다운로드

3. Google drive api를 이용해서 다운로드

 

나는 mp3파일을 다운로드 해야했으므로, 파일이 중간에 깨지면 (스트림이 중단되면) 온전한 파일로 인식하지 못해 문제가 생겼다. 그래서 1->2>을 거쳐 3번 방법을 시도해보기에 이르렀다. 

물론 wget 도 시도했지만 역시나 실패..

 

1. requests

먼저 requests로 다운로드 하는 방법이다. 필자는 mp3파일이라서 사용하지 못했지만 일반적인 파일에는 적용가능하리라.

import requests

def download_audio(url, filename="temp_audio.mp3"):
    """Google Drive에서 MP3 파일 다운로드 (Windows 호환)"""
    try:
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            with open(filename, "wb") as f:
                for chunk in response.iter_content(chunk_size=8192):
                    f.write(chunk)
            logging.info(f"✅ MP3 다운로드 완료: {filename}")
            return filename
        else:
            logging.error(f"❌ MP3 다운로드 실패 (HTTP {response.status_code})")
            return None
    except Exception as e:
        logging.error(f"❌ 다운로드 오류: {e}")
        return None

 

 

2. gdown 

 

import gdown 

def download_audio(url, filename="temp_audio.mp3"):
    """Google Drive에서 MP3 파일 다운로드 (`gdown` 사용)"""
    try:
        file_id = extract_drive_file_id(url)
        if not file_id:
            logging.error(f"❌ 올바르지 않은 Google Drive 링크: {url}")
            return None

        drive_download_url = f"https://drive.google.com/uc?id={file_id}"
        gdown.download(drive_download_url, filename, quiet=False)

 

이하는 mp3의 경우 파일 유효성 검사코드

if not filename.endswith(".mp3") or os.path.getsize(filename) < 1000:
    logging.error(f"❌ MP3 파일이 손상되었거나 올바르지 않음: {filename}")
    return None

 

 

3. Google Drive API 사용

from google.oauth2 import service_account


SERVICE_ACCOUNT_FILE = "setting/credentials.json"

SCOPES = [
    "https://www.googleapis.com/auth/spreadsheets",  # Google Sheets API 권한
    "https://www.googleapis.com/auth/drive"         # Google Drive API 권한 
]
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
drive_service = build("drive", "v3", credentials=creds)

def download_audio_from_drive(file_id, filename="temp_audio.mp3"):
    """Google Drive에서 MP3 파일 다운로드 (Google Drive API 사용)"""
    try:
        request = drive_service.files().get_media(fileId=file_id)
        with open(filename, "wb") as f:
            f.write(request.execute())

        # ✅ 다운로드된 파일이 실제 MP3인지 확인
        if not filename.endswith(".mp3") or os.path.getsize(filename) < 1000:  # 1KB 이하 파일은 손상 가능성 있음
            logging.error(f"❌ MP3 파일이 손상되었거나 올바르지 않음: {filename}")
            return None

        logging.info(f"✅ MP3 다운로드 완료: {filename}")
        return filename

 

 

위 코드를 실행하려면 , pip는 최신버전으로 해야함 주의

pip install google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2

 

728x90

댓글