Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- from apiclient import errors
- # If modifying these scopes, delete the file token.pickle.
- class GDrive:
- def __init__(self):
- self.service = None
- self.get_service()
- def get_service(self):
- creds = None
- SCOPES = ['https://www.googleapis.com/auth/drive']
- 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(
- 'credentials.json', SCOPES)
- creds = flow.run_local_server(port=0)
- with open('token.pickle', 'wb') as token:
- pickle.dump(creds, token)
- self.service = build('drive', 'v3', credentials=creds)
- def list(self, query, fields):
- request = self.service.files().list(q=query, fields=fields)
- files = []
- if request is not None:
- try:
- results = request.execute()
- items = results.get('files', [])
- if not items:
- return []
- else:
- for item in items:
- #print(u'{0} ({1})'.format(item['name'], item['id']))
- files.append([item['name'], item['id']])
- return files
- except Exception as err:
- print("There was an Error:")
- print(err)
- return []
- def list_folders(self, qtype):
- querys = ["mimeType='application/vnd.google-apps.folder'", "mimeType!='application/vnd.google-apps.folder'"]
- fields = "nextPageToken, files(id, name)"
- return self.list(querys[qtype], fields)
- def list_files_in_folder(self, folder_id):
- querys= "'%s' in parents"%folder_id
- fields = "nextPageToken, files(id,parents,name)"
- return self.list(querys, fields)
- def create_folder(self, parent, foldername):
- file_metadata = {
- 'name': foldername,
- 'mimeType': 'application/vnd.google-apps.folder',
- 'parents': [parent]
- }
- try:
- file = self.service.files().create(body=file_metadata, fields='id').execute()
- return file.get('id')
- except errors.HttpError as err:
- return ""
- def upload_sheet(self, sheet, path, parent):
- file_metadata = {
- 'name': sheet,
- #'mimeType': 'application/vnd.google-apps.unknown'#,
- 'parents': [parent]
- }
- print(path+sheet+".xlsx")
- media = MediaFileUpload(path+sheet+".xlsx", mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
- file = self.service.files().create(body=file_metadata,
- media_body=media,
- fields='id').execute()
- if __name__ == '__main__':
- drive =GDrive()
- #drive.list_files()
- #print("")
- #print("")
- #drive.list_folders(1)
- drive.create_folder("1LszjbR0VRCR5sjHXqKu52sbr4yI0wC9h", "DriveAPIFolder")
- drive.list_files_in_folder("1LszjbR0VRCR5sjHXqKu52sbr4yI0wC9h")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement