Advertisement
AceScottie

DriveTest.py

Aug 22nd, 2019
433
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.63 KB | None | 0 0
  1. from __future__ import print_function
  2. import pickle
  3. import os.path
  4. from googleapiclient.discovery import build
  5. from google_auth_oauthlib.flow import InstalledAppFlow
  6. from google.auth.transport.requests import Request
  7. from apiclient.http import MediaFileUpload
  8. from apiclient import errors
  9. # If modifying these scopes, delete the file token.pickle.
  10. class GDrive:
  11.     def __init__(self):
  12.         self.service = None
  13.         self.get_service()
  14.     def get_service(self):
  15.         creds = None
  16.         SCOPES = ['https://www.googleapis.com/auth/drive']
  17.         if os.path.exists('token.pickle'):
  18.             with open('token.pickle', 'rb') as token:
  19.                 creds = pickle.load(token)
  20.         # If there are no (valid) credentials available, let the user log in.
  21.         if not creds or not creds.valid:
  22.             if creds and creds.expired and creds.refresh_token:
  23.                 creds.refresh(Request())
  24.             else:
  25.                 flow = InstalledAppFlow.from_client_secrets_file(
  26.                     'credentials.json', SCOPES)
  27.                 creds = flow.run_local_server(port=0)
  28.             with open('token.pickle', 'wb') as token:
  29.                 pickle.dump(creds, token)
  30.  
  31.         self.service = build('drive', 'v3', credentials=creds)
  32.     def list(self, query, fields):
  33.         request = self.service.files().list(q=query, fields=fields)
  34.         files = []
  35.         if request is not None:
  36.             try:
  37.                 results = request.execute()
  38.                 items = results.get('files', [])
  39.                 if not items:
  40.                     return []
  41.                 else:
  42.                     for item in items:
  43.                         #print(u'{0} ({1})'.format(item['name'], item['id']))
  44.                         files.append([item['name'], item['id']])
  45.                     return files
  46.             except Exception as err:
  47.                 print("There was an Error:")
  48.                 print(err)
  49.                 return []
  50.     def list_folders(self, qtype):
  51.         querys = ["mimeType='application/vnd.google-apps.folder'",  "mimeType!='application/vnd.google-apps.folder'"]
  52.         fields = "nextPageToken, files(id, name)"
  53.         return self.list(querys[qtype], fields)
  54.     def list_files_in_folder(self, folder_id):
  55.         querys= "'%s' in parents"%folder_id
  56.         fields = "nextPageToken, files(id,parents,name)"
  57.         return self.list(querys, fields)
  58.     def create_folder(self, parent, foldername):
  59.         file_metadata = {
  60.             'name': foldername,
  61.             'mimeType': 'application/vnd.google-apps.folder',
  62.             'parents': [parent]
  63.         }
  64.         try:
  65.             file = self.service.files().create(body=file_metadata, fields='id').execute()
  66.             return file.get('id')
  67.         except errors.HttpError as err:
  68.             return ""
  69.     def upload_sheet(self, sheet, path, parent):
  70.         file_metadata = {
  71.             'name': sheet,
  72.             #'mimeType': 'application/vnd.google-apps.unknown'#,
  73.             'parents': [parent]
  74.         }
  75.         print(path+sheet+".xlsx")
  76.         media = MediaFileUpload(path+sheet+".xlsx", mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  77.         file = self.service.files().create(body=file_metadata,
  78.                                     media_body=media,
  79.                                     fields='id').execute()
  80. if __name__ == '__main__':
  81.     drive =GDrive()
  82.     #drive.list_files()
  83.     #print("")
  84.     #print("")
  85.     #drive.list_folders(1)
  86.     drive.create_folder("1LszjbR0VRCR5sjHXqKu52sbr4yI0wC9h", "DriveAPIFolder")
  87.     drive.list_files_in_folder("1LszjbR0VRCR5sjHXqKu52sbr4yI0wC9h")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement