Google Drive 업로드 API 를 왜 쓰냐? 

 여러 파일을 한꺼번에 올릴 수 있다는 것이고, 나같은 경우는 웹호스팅 서비스를 아주 간단하게 시험해 볼때 이미지 저장소로 사용하면서 이미지 로딩에 사용할 사진들을 올려놓고 테스트에 활용할 수 있다. 물론 호스팅 업체 서버를 이용해서 정식으로 할때는 필요없지만 . 

 아래 구글에서 제공하는 Quick Start 사이트를 이용하면 현재 계정에 올라가 있는 파일 리스트 10개와 폴더 ID를 가지고 올 수 있다. 사실 이것만 되면 나머지는 메뉴얼 보면서 하면 금방 할 수 있다. 

 

Python Quickstart  |  Drive API  |  Google Developers

 

Python Quickstart  |  Drive API  |  Google Developers

Send feedback Python Quickstart Complete the steps described in the rest of this page to create a simple Python command-line application that makes requests to the Drive API. Prerequisites To run this quickstart, you need the following prerequisites: Pytho

developers.google.com

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()

위 코드 블록을 보면 "storage.json" 파일은 이전 포스팅에서 json 다운로드 하면 얻을 수 있다. 아마 storage.json으로 저장이 안되면 이름을 storage.json으로 변경해 준다. 아래 참조

'코딩해보기/Google Drive API' 카테고리의 글 목록 :: 별일 없이 산다 (tistory.com)

 

'코딩해보기/Google Drive API' 카테고리의 글 목록

 

elecsog.tistory.com

 

일단 위 코드를 실행을 하면 구글 계정 선택하라고 하면 위 링크에서 설정한 아이디 설정하면 "token.json" 파일이 생기면서 다음부터는 계정 설정 안해도 된다. 

 

여기서 얻어 낸 폴더 ID는 잘 가지고 있길 바란다. 파일 업로드까지 해보려고 했는데 너무 졸리다. 다음 포스팅에서 쓰련다. 

'코딩해보기 > Google Drive API' 카테고리의 다른 글

1_Google_Clouds_Console_Setting  (0) 2022.08.15

+ Recent posts