Skip to content

Google Drive

구글 드라이브.

Categories

API 사용을 위한 OAuth 등록 절차

  • 구글 클라우드 콘솔 https://console.cloud.google.com/ 접속.
  • 프로젝트 선택 (없다면 만들자)
  • 상단 "탐색" 버튼 (햄버거 모양) 눌러서 "API 및 서비스" > "라이브러리" 클릭.
  • "API 및 서비스 검색" 입력란에 "Google Drive API" 입력하여 들어간다.
  • "사용" 버튼을 클릭한다. (이미 클릭했다면 "관리" 버튼으로 바뀐다)
  • "OAuth 동의 화면" 구성하지 않았다면, "동의 화면 구성" 클릭하여 구성한다.
  • "사용자 인증 정보" 클릭, "사용자 인증 정보 만들기" > "OAuth 클라이언트 ID" 클릭.
  • 어플리케이션 유형은 "웹 어플리케이션" 클릭.
  • 웹 클라이언트 이름 입력
Google_Drive_API_OAuth_Register_-_01.png
Google_Drive_API_OAuth_Register_-_02.png
Google_Drive_API_OAuth_Register_-_03.png
Google_Drive_API_OAuth_Register_-_04.png

Python OAuth Example

데스크톱 애플리케이션의 사용자 인증 정보 승인

최종 사용자로 인증하고 앱의 사용자 데이터에 액세스하려면 OAuth 2.0 클라이언트 ID를 하나 이상 만들어야 합니다. 클라이언트 ID는 Google OAuth 서버에서 단일 앱을 식별하는 데 사용됩니다. 앱이 여러 플랫폼에서 실행되는 경우 플랫폼마다 별도의 클라이언트 ID를 만들어야 합니다.

  1. Google Cloud 콘솔에서 메뉴 menu > API 및 서비스 > 사용자 인증 정보로 이동합니다.
  2. 사용자 인증 정보로 이동
  3. 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 클릭합니다.
  4. 애플리케이션 유형 > 데스크톱 앱을 클릭합니다.
  5. 이름 필드에 사용자 인증 정보의 이름을 입력합니다. 이 이름은 Google Cloud Console에만 표시됩니다.
  6. 만들기를 클릭합니다. OAuth 클라이언트 생성 화면이 표시되어 새로운 클라이언트 ID와 클라이언트 보안 비밀번호가 표시됩니다.
  7. OK를 클릭합니다. 새로 생성된 사용자 인증 정보가 OAuth 2.0 클라이언트 ID 아래에 표시됩니다.
  8. 다운로드한 JSON 파일을 credentials.json로 저장하고 이 파일을 작업 디렉터리로 이동합니다.

Google 클라이언트 라이브러리 설치

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

샘플 코딩

작업 디렉터리에 quickstart.py이라는 파일을 만듭니다:

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']


def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('drive', 'v3', credentials=creds)

        # Call the Drive v3 API
        results = service.files().list(
            pageSize=10, fields="nextPageToken, files(id, name)").execute()
        items = results.get('files', [])

        if not items:
            print('No files found.')
            return
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))
    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')


if __name__ == '__main__':
    main()

실행

다음과 같은 느낌으로 출력된다:

Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=310991267121-amtie57drl8o3dheg6m4uk4mcuj1rr15.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A51797%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly&state=M4ldK0mAqqWsn15uUwbeU10FIQS4iq&access_type=offline

브라우저에서 해당 URL로 접속한 후 OK 누르면 파일 목록을 출력할 수 있다. 두 번째 실행 부터는 token.json파일이 있으므로 인증은 스킵된다.

다음 단계

File Upload/Download

See also

Favorite site

API

Guide