안녕하세요! 이번 포스팅에서는 Google Drive API를 사용해 파일이나 폴더를 검색하고, 폴더를 생성하고, 파일을 업로드하는 방법을 소개하겠습니다.
0. 구글 드라이브 API 설정
먼저 Google Drive API를 사용하기 위해서는 API 자격 증명을 설정해야 합니다. 이를 위해 서비스 계정(Service Account)을 생성하고, 해당 계정의 인증 파일을 다운로드해야 합니다. 구글 클라우드 콘솔에서 API 사용을 활성화하고 자격 증명 JSON 파일을 생성한 후, 코드에서 사용할 수 있습니다.
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
# 구글 드라이브 API 자격 증명 파일 경로
SERVICE_ACCOUNT_FILE = 'api_key.json'
# API에 필요한 범위
SCOPES = ['https://www.googleapis.com/auth/drive']
# 구글 드라이브 클라이언트 생성
credentials = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)
위 코드를 통해 구글 드라이브 API를 사용할 준비가 완료됩니다. api_key.json 파일은 서비스 계정의 자격 증명을 포함하고 있어, 구글 드라이브에 접근할 수 있게 해줍니다.
1. 파일 및 폴더 검색하기
Google Drive에서 파일이나 폴더를 검색하기 위해서는 files().list() 메서드를 사용하여 쿼리를 작성해야 합니다. 이를 통해 드라이브 내에서 특정 파일 또는 폴더가 존재하는지 확인할 수 있습니다. 예를 들어, 특정 폴더 안에서 이름이 동일한 폴더가 있는지 확인하는 코드는 아래와 같습니다.
def search_file_or_folder(service, search_name, parent_folder_id):
# 검색 조건 설정
query = f"'{parent_folder_id}' in parents and name='{search_name}' and trashed=false"
response = service.files().list(q=query, spaces='drive',
fields='files(id, name)', supportsAllDrives=True).execute()
files = response.get('files', [])
if files:
print(f"'{search_name}' found with ID: {files[0].get('id')}")
return files[0].get('id')
else:
print(f"'{search_name}' not found.")
return None
코드설명
- search_file_or_folder(): 특정 이름의 파일, 폴더를 검색하고 해당 이름을 가진 파일, 폴더의 ID를 반환함.
- parent_folder_id: 검색하려는 구글 드라이브 폴더의 ID입니다. URL의 뒷부분을 복사해 사용
(예: https://drive.google.com/drive/folders/1tN1cdnz7tmKD0hu0~)
2. 폴더 생성하기
폴더를 생성하기 위해서는 Google Drive API의 files().create() 메서드를 사용하여 새 폴더를 만들 수 있습니다. 아래 코드는 주어진 상위 폴더 안에 새로운 폴더를 생성하는 예시입니다.
def create_folder(service, folder_name, parent_folder_id):
file_metadata = {
'name': folder_name,
'mimeType': 'application/vnd.google-apps.folder',
'parents': [parent_folder_id],
}
folder = service.files().create(body=file_metadata, fields='id', supportsAllDrives=True).execute()
return folder.get('id')
3. 파일 업로드하기
파일을 구글 드라이브에 업로드하려면 MediaFileUpload 클래스를 사용하여 파일을 전송하고, files().create() 메서드를 통해 파일을 업로드할 수 있습니다. 아래 코드는 지정된 경로의 파일을 특정 폴더에 업로드하는 예시입니다.
from googleapiclient.http import MediaFileUpload
import os
def upload_file(service, file_path, parent_folder_id):
file_name = os.path.basename(file_path)
media = MediaFileUpload(file_path, resumable=True)
file_metadata = {
'name': file_name,
'parents': [parent_folder_id],
}
file = service.files().create(body=file_metadata, media_body=media, fields='id', supportsAllDrives=True).execute()
print(f"File '{file_name}' uploaded with ID: {file.get('id')}")
코드 설명
upload_file() 함수는 파일 경로와 부모 폴더 ID를 받아, 해당 폴더에 파일을 업로드합니다. 파일 업로드가 성공하면 파일의 ID를 반환하여 확인할 수 있습니다.
Google Drive API를 사용한 파일, 폴더 검색, 새로운 폴더 생성, 파일 업로드 방법을 알아보았습니다. 필요하신 분들께 도움이 되었길 바랍니다. 글에서 소개한 내용은 Google Drive API 공식문서를 참고하였습니다. 공식문서에는 파일 다운로드, 삭제, 공유 등의 추가적인 기능이 잘 정리되어 있으니 궁금하신 분들은 읽어보는 것을 추천드립니다.