반응형
googledriveapi

Upload File to Google Drive

Prepare

구글 사이트에서 준비 작업이 필요하다.
https://console.developers.google.com/flows/enableapi?apiid=drive
프로젝트 생성
Google Drive API 사용.
Credential에서 OAuth 화면.
Product Name 입력.
json 파일 다운 로드 (client_drive.json).
작업디렉터리로 파일 이동.

# 파이썬 패키지 설치
pip install google-api-python-client

토큰 생성

from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

scopes = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('storage.json')
creds = store.get()

try :
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

if not creds or creds.invalid:
    print('make new cred')
    flow = client.flow_from_clientsecrets('client_drive.json', scopes)
    creds = tools.run_flow(flow, store, flags) if flags else tools.run_flow(flow, store)


콘솔로 위의 파일을 실행하면, 웹브라우저가 뜨고, 구글 인증/로그인을 하면 된다. 현재 폴더에 storage.json 이라는 토큰이 생김. 보안 파일이므로 중요보관.

파일 업로드

from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

store = file.Storage('storage.json')
creds = store.get()
drive = build('drive', 'v3', http=creds.authorize(Http()))
uploadfiles=( ('a.txt'),)
for f in uploadfiles:
    fname = f
    metadata={'name':fname, 'mimeType':None}
    res = drive.files().create(body=metadata, media_body=fname).execute()
    if res:
        print('upload %s'%fname)
        

파일 다운로드

파일ID는 구글드라이브에서 해당 파일 공유하기해서 링크 주소를 얻어오면 id값이 들어있다.

import io
from apiclient.http import MediaIoBaseDownload

results = drive.files().list(pageSize=10,fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print(item)
        print('{0} ({1})'.format(item['name'], item['id']))

#https://drive.google.com/open?id=1SY8FS1QcGTknYJjEUgaqj1ucWEtESTn3
# request = drive.files().export_media(fileId='a.txt', mimeType=EXCEL)
request = drive.files().get_media(fileId='1SY8FS1QcGTknYJjEUgaqj1ucWEtESTn3')
fh = io.FileIO('b.txt', 'wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print('Download %d%%.' % int(status.progress() * 100))
        

CoLab에서 구글 드라이브 파일 가져오기


# Install the PyDrive wrapper & import libraries.  
# This only needs to be done once per notebook. 
!pip install -U -q PyDrive 
from pydrive.auth import GoogleAuth 
from pydrive.drive import GoogleDrive 
from google.colab import auth 
from oauth2client.client import GoogleCredentials 

# Authenticate and create the PyDrive client.  
# This only needs to be done once per notebook. 
auth.authenticate_user() 
gauth = GoogleAuth() 
gauth.credentials = GoogleCredentials.get_application_default() 
drive = GoogleDrive(gauth) 

# Download a file based on its file ID.  
#  
# A file ID looks like: laggVyWshwcyP6kEI-y_W3P8D26sz 
file_id = 'REPLACE_WITH_YOUR_FILE_ID' 
downloaded = drive.CreateFile({'id': file_id}) print('Downloaded content "{}"'.format(downloaded.GetContentString()))  

  


Written with StackEdit.

'Python' 카테고리의 다른 글

Jupyter Notebook 멀티라인출력  (0) 2019.09.19
진행(progress)바/ tqdm  (2) 2019.08.28
Fourier Transform Python  (1) 2019.08.02
[UI] Qt5  (0) 2019.05.17
두 선분의 교차여부 체크  (0) 2019.04.11

+ Recent posts