티스토리 뷰

<Functions>

  • Upload files
  • Download files
  • Write spreadsheets

<Preparations>

  • Google APIs > User Authentication > ... >사용자 인증정보 만들기 > OAuth Client ID > 'Create(생성)'
  • "pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib"
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient.http import MediaFileUpload, MediaIoBaseDownload
import os, io
import gspread


class cGoogleDrive:
    SCOPES = [
        'https://www.googleapis.com/auth/drive',
        'https://spreadsheets.google.com/feeds'
        ]
    CLIENT_SCERET_FILE = 'client_secret_....json'
    APPLICATIONNAME = '[I2B] Google Drive API Test'

    def __init__(self):
        creds = None
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        # 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(
                    CLIENT_SCERET_FILE, SCOPES)
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        self.DriveCredentials = creds
        self.DriveService  = build('drive', 'v3', credentials=creds)

    def ListFiles(self, size):
        results = self.DriveService.files().list(
            pageSize=size, 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(u'{0} ({1})'.format(item['name'], item['id']))

    def UploadFile(self, filename, filepath, mimetype):
        file_metadata = {'name':filename}
        media = MediaFileUpload(filepath, mimetype=mimetype)
        file = self.DriveService.files().create(body=file_metadata, media_body=media, fields='id').execute()
        print('file ID: %s' %file.get('id'))

    def DownloadFile(self, file_id, filepath):
        request = self.DriveService.files().get_media(fileId=file_id)
        fh = io.BytesIO()
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print("Download %d%%." %int(status.progress()*100))
            with io.open(filepath, 'wb') as f:
                fh.seek(0)
                f.write(fh.read())

    def CreateFolder(self, name):
        file_metadata = {
            'name':name,
            'mimeType': 'application/vnd.google-apps.folder'
        }
        file = self.DriveService.files().create(body=file_metadata, fields='id').execute()
        print('Folder ID: %s' %file.get('id'))

    def SearchFiles(self, size, query):
        results = self.DriveService.files().list(
            pageSize=size, fields="nextPageToken, files(id, name)", q=query).execute()
        items = results.get('files', [])

        if not items:
            print('No files found.')
        else:
            print('Files:')
            for item in items:
                print(u'{0} ({1})'.format(item['name'], item['id']))

    def GetSpreadSheet(self, fileName): 
        gc = gspread.authorize(self.DriveCredentials)
        gs = gc.create(fileName)

        return gs

    def WriteSpread(self, googleSpread, sheetName, cellInfos):
        worksheet = googleSpread.add_worksheet(title=sheetName, rows='100', cols='10')
        rowNo =1
        count11 = 0
        for cellInfo1 in cellInfos:
            linkAddress1 = cellInfo1['address']
            linkTitle1 = cellInfo1['title']
            linkBody1 = cellInfo1['body']
            overlapped1 = False
            count21 = 0
            for cellInfo2 in cellInfos:
                if(count21 >= count11):
                    break
                if linkAddress1 == cellInfo2['address']:
                    overlapped1 = True
                    break
                count21 += 1
            if not overlapped1:
                worksheet.update_acell("B"+str(rowNo), linkAddress1)
                worksheet.update_acell("C"+str(rowNo), linkTitle1)
                worksheet.update_acell("D"+str(rowNo), linkBody1)
                rowNo += 1
            count11 += 1
        # Sorry, you have exceeded your sharing quota
        # --> Logout and re-login

    def TransferSheet(self, googleSpread):
        googleSpread.share('bilient2014@gmail.com', perm_type='user', role='owner')

    def UploadXLSXFiles(self):

 

반응형